﻿using System;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
using Com.DAO;
using Com.Object;
using System.Data;
using System.Xml;
using SourceCode.Workflow.Client;
using SourceCode.Workflow.Management;
using WF.Common;
using WF.BusinessObject;
using WF.Model;
using System.Collections.Generic;
using System.Reflection;

namespace WF.Common
{
    /// <summary>
    /// WorkFlowHelper 的摘要说明。

    /// </summary>
    public class WorkFlowHelper
    {
        public WorkFlowHelper()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }

        #region 流程类型 WF_APPLY_TYPE
        /// <summary>
        /// 组织单元新建审批
        /// </summary>
        public const string WF_APPLY_TYPE_DEPT_ADD = "深圳组织单元新建审批";

        /// <summary>
        /// 组织单元调整审批
        /// </summary>
        public const string WF_APPLY_TYPE_DEPT_ADJUST = "深圳组织单元调整审批";

        /// <summary>
        /// 组织单元撤销审批
        /// </summary>
        public const string WF_APPLY_TYPE_DEPT_CANCLE = "深圳组织单元撤销审批";

        /// <summary>
        /// 职员入职审批
        /// </summary>
        public const string WF_APPLY_TYPE_EMP_JOIN = "深圳职员入职审批";

        /// <summary>
        /// 职员转正审批
        /// </summary>
        public const string WF_APPLY_TYPE_EMP_PASS = "深圳职员转正审批";

        /// <summary>
        /// 职员异动审批
        /// </summary>
        public const string WF_APPLY_TYPE_EMP_ADJUST = "深圳职员异动审批";

        /// <summary>
        /// 职员离职审批
        /// </summary>
        public const string WF_APPLY_TYPE_EMP_DIMISSION = "深圳职员离职审批";

        /// <summary>
        /// 利尊考勤审批
        /// </summary>
        public const string WF_APPLY_TYPE_KQAPPLY = "上海中原中介部考勤审批";
        #endregion

        #region 成交报告当前进程状态常量定义

        public const string CONTRACT_ALREADY_REPORT = "IsReportAchievement";//已上数

        #endregion 成交报告当前进程状态常量定义


        #region 审批状态常量

        //WF_INSTANCE_STATE
        //其他状态增加类似的常量
        public const string WF_INSTANCE_PRESUBMIT_STATE = "待提交";
        public const string WF_INSTANCE_APPROVING_STATE = "审批中";
        public const string WF_INSTANCE_COMPLETED_STATE = "已完成";
        #endregion

        /// <summary>
        /// 获取K2连接
        /// </summary>
        /// <returns></returns>
        public static Connection GetK2Connection()
        {
            try
            {
                Connection oK2Connection = new Connection();
                string K2Server = System.Configuration.ConfigurationManager.AppSettings["PlanServer"];

                string mngUserID = System.Configuration.ConfigurationManager.AppSettings["MngUserID"].ToString();
                string mngUserPasswrod = WF.Security.Cryptography.DESDecryption(System.Configuration.ConfigurationManager.AppSettings["MngUserPassword"].ToString());
                string connectionString = "[;];Authentication=Windows;Domain=centaline;User=" + mngUserID + ";Password=" + mngUserPasswrod + "";

                oK2Connection.Open(K2Server, connectionString);
                return oK2Connection;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 得到K2连接串

        /// </summary>
        /// <returns></returns>
        public static string GetK2ManagementServerConnectionString()
        {
            SourceCode.Hosting.Client.BaseAPI.SCConnectionStringBuilder connectionString;
            connectionString = new SourceCode.Hosting.Client.BaseAPI.SCConnectionStringBuilder();
            connectionString.Authenticate = true;
            connectionString.WindowsDomain = "CENTALINE";
            connectionString.SecurityLabelName = "K2";
            connectionString.UserID = System.Configuration.ConfigurationManager.AppSettings["MngUserID"].ToString();
            connectionString.Password = WF.Security.Cryptography.DESDecryption(System.Configuration.ConfigurationManager.AppSettings["MngUserPassword"].ToString());
            connectionString.Host = System.Configuration.ConfigurationManager.AppSettings["PlanServer"];
            connectionString.Integrated = true;
            connectionString.IsPrimaryLogin = true;
            connectionString.Port = 5555;

            return connectionString.ToString();
        }

        /// <summary>
        /// 通过管理员找到对应WorkListItem的状态

        /// </summary>
        /// <param name="processFullName"></param>
        /// <param name="activityName"></param>
        /// <param name="destination"></param>
        /// <returns></returns>      
        public static SourceCode.Workflow.Management.WorklistItem.WorklistStatus GetWorkListItemStatus(string processFullName, string activityName, string destination)
        {
            SourceCode.Workflow.Management.Criteria.WorklistCriteriaFilter
                worklistCriteriaFilter = new SourceCode.Workflow.Management.Criteria.WorklistCriteriaFilter();
            worklistCriteriaFilter.REGULAR_FILTER(WorklistFields.ProcessFullName,
                                                    SourceCode.Workflow.Management.Criteria.Comparison.Equals,
                                                    processFullName,
                                                    SourceCode.Workflow.Management.Criteria.RegularFilter.FilterCondition.AND);
            worklistCriteriaFilter.AddRegularFilter(WorklistFields.ActionName,
                                                    SourceCode.Workflow.Management.Criteria.Comparison.Equals,
                                                    activityName);
            worklistCriteriaFilter.AddRegularFilter(WorklistFields.Destination,
                                                    SourceCode.Workflow.Management.Criteria.Comparison.Like,
                                                    destination);

            WorkflowManagementServer wms = new WorkflowManagementServer();
            wms.Open(GetK2ManagementServerConnectionString());


            SourceCode.Workflow.Management.WorklistItems wlis = wms.GetWorklistItems(worklistCriteriaFilter);
            SourceCode.Workflow.Management.WorklistItem.WorklistStatus ret = SourceCode.Workflow.Management.WorklistItem.WorklistStatus.Completed;
            foreach (SourceCode.Workflow.Management.WorklistItem wli in wlis)
            {
                ret = wli.Status;
            }
            return ret;
        }




        /// <summary>
        /// 新增工作流实例

        /// </summary>
        /// <param name="dataManager"></param>
        /// <param name="applyType">工作流类型名称</param>
        /// <param name="bizDataID">业务数据ID</param>
        /// <param name="curState">流程当前状态</param>
        /// <param name="applyBy">申请人帐号</param>
        /// <param name="applyEmpID">申请人EMPID</param>
        /// <param name="applicantName">申请人名称</param>
        /// <param name="applyDeptID">申请人所属部门</param>
        /// <param name="isFinished">是否完成</param>
        /// <returns>工作流申请实例ApplyID</returns>
        /// </summary>
        public static WF_ApplyInstanceEntity AddWorkFlowInstance(
            WF.DAL.WFDBDataContext dataContext,
            string applyTypeName,
            string bizDataID,
            UserProfile userProfile
            )
        {
            string applyID = System.Guid.NewGuid().ToString();
            string curState = WorkFlowHelper.WF_INSTANCE_PRESUBMIT_STATE;

            WF_ApplyInstanceEntity newEntity = new WF_ApplyInstanceEntity();
            newEntity.ID = applyID;
            newEntity.ApplyBy = userProfile.LoginName; ;
            newEntity.ApplicantName = userProfile.Empname;
            newEntity.ApplyDate = System.DateTime.Now;
            newEntity.ApplyDeptID = userProfile.DeptID;
            newEntity.ApplyEmpID = userProfile.EmpID;
            newEntity.ApplyTypeID = GetApplyTypeID(dataContext, applyTypeName);
            newEntity.ApplyTypeName = applyTypeName;
            newEntity.BizDataID = bizDataID;
            newEntity.CurrentStepOrder = 0;
            newEntity.CurState = curState;
            newEntity.IsFinished = 0;

            WF.BusinessObject.WF_ApplyInstance inst = new WF_ApplyInstance(dataContext);
            inst.Add(newEntity);

            return newEntity;
        }

        private static string GetApplyTypeID(DAL.WFDBDataContext dataContext, string applyTypeName)
        {
            WF_ApplyType bo = new WF_ApplyType(dataContext);
            var obj = bo.GetByApplyType(applyTypeName);
            return string.IsNullOrEmpty(obj.ID) ? "" : obj.ID;
        }

        /// <summary>
        /// 更新工作流实例

        /// </summary>
        /// <param name="dataContext"></param>                
        /// <param name="curState">流程当前状态</param>       
        /// <param name="isFinished">是否完成</param>
        /// <returns>工作流申请实例ApplyID</returns>
        public static void UpdateWorkFlowInstance(
            WF.DAL.WFDBDataContext dataContext,
            string applyID,
            short isWFSubmit,
            int procInstID,
            string folio,
            short isFinished,
            string curState)
        {
            if (string.IsNullOrEmpty(curState))
            {
                curState = WorkFlowHelper.WF_INSTANCE_APPROVING_STATE;
            }
            WF.Model.WF_ApplyInstanceEntity newEntity = new Model.WF_ApplyInstanceEntity();
            newEntity.ID = applyID;
            newEntity.IsWFSubmit = isWFSubmit;
            newEntity.ProcInstID = procInstID;
            newEntity.Folio = folio;
            newEntity.IsFinished = isFinished;
            newEntity.CurState = curState;

            WF.BusinessObject.WF_ApplyInstance inst = new WF_ApplyInstance(dataContext);
            inst.Update(newEntity);
        }


        /// <summary>
        /// 保存工作流申请单明细
        /// </summary>
        /// <param name="dataManager"></param>
        /// <param name="applyID"></param>
        /// <param name="ds"></param>
        public static void AddWorkFlowInstanceDetail(DataManager dataManager, string applyID, DataSet ds)
        {
            string bizDataID = "";
            BusinessEntiry be;
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                bizDataID = row[0].ToString();
                be = new BusinessEntiry(dataManager, "WF_ApplyInstanceDetail", "DetailID");
                be.SetProperty("DetailID", CentaUtil.GetNewGUID());
                be.SetProperty("ApplyID", applyID);
                be.SetProperty("BizDataID", bizDataID);
                be.Save(!dataManager.IsBeginTrasaction);
            }
        }

        /// <summary>
        /// 提交K2流程实例后设置申请单的提交状态标志

        /// </summary>
        /// <param name="dataManager"></param>
        /// <param name="applyID"></param>
        public static void SetWFSubmitFlag(DataManager dataManager, string applyID)
        {
            BusinessEntiry be = new BusinessEntiry(dataManager, "WF_ApplyInstance", "ApplyID");
            if (be.OpenByKeyValue(applyID))
            {
                be.SetProperty("IsWFSubmit", "1");
                be.Save(!dataManager.IsBeginTrasaction);
            }
        }

        /// <summary>
        /// 根据ApplyType名称获取ApplyTypeID
        /// </summary>
        /// <param name="dataManager"></param>
        /// <param name="applyType"></param>
        /// <returns></returns>
        public static string GetApplyTypeID(DataManager dataManager, string applyType)
        {
            return GetApplyTypeFieldValueByType(dataManager, applyType, "ApplyTypeID"); ;
        }

        public static string GetApplyTypeFieldValueByType(DataManager dataManager, string applyType, string field)
        {
            string rtn = "";
            string sql = String.Format("select * from CFG_WFApplyType where applyType = '{0}'", applyType);
            SqlDataReader rs = dataManager.selectReader(sql);
            if (rs.Read())
            {
                rtn = rs[field].ToString();
            }
            rs.Close();
            return rtn;
        }



        #region ===StartNewProcess===
        /// <summary>
        /// 启动新流程

        /// </summary>
        /// <param name="dataManager"></param>
        /// <param name="empID">发起人ID</param>
        /// <param name="applyID">申请单ID</param>
        /// <param name="applyType">流程类型</param>
        /// <returns></returns>
        //public static bool StartNewProcess(DataManager dataManager, string empID, string applyID, string applyType, System.Web.UI.Page page)
        //{
        //    SourceCode.Workflow.Client.ProcessInstance oNewProcessInstance;

        //    Connection oK2Connection = GetK2Connection();

        //    string processName = GetApplyTypeFieldValueByType(dataManager, applyType, "K2WorkflowName");
        //    try
        //    {
        //        //Create New Process Instance 

        //        //设置流程DataFields的结构并赋值。

        //        string data = GetDataFieldsXML(dataManager, empID, applyID, applyType);

        //        oNewProcessInstance = oK2Connection.CreateProcessInstance(processName);

        //        DataSet ds = new DataSet();
        //        System.IO.StringReader sr = new System.IO.StringReader(data);
        //        ds.ReadXml(sr);
        //        Com.Object.Fields fd = new Com.Object.Fields();
        //        fd.LoadDataFromDataSet(ds, true);

        //        //流程发起人姓名

        //        string originatorName = "";

        //        //日志记录用

        //        string content = "";
        //        string opNo = "";
        //        string applyName = applyType;
        //        string folio = "";

        //        /*
        //            * OriginatorName		：发起人
        //            * ApplyID				：申请单号

        //            * CaseID				: 
        //            * DeptID				：发起人所属部门

        //            * IsCentaChangeOwner	：是否经中原过户
        //            * IsExistArea			：是否存在二级区域

        //            * Trade					：交易类型（买卖/租赁/买卖代办手续/租赁代办手续）

        //            * ContractReportNo		：成交报告编号

        //            * OriginatorJobName		：发起人职位
        //            * DeptName				：申请人所属部门

        //            * ContractPrice			：成交价格

        //            * ContractEmpName		：成交人
        //            * ContractDeptName		：成交部门

        //            * ContractDeptID		：成交部门ID
        //            * PaymentMoney			：放款金额

        //            * AreaName				：成交报告所属二级区域

        //            * OwnerName				：卖方姓名

        //            * CustomerName			：买方姓名

        //                                * */
        //        ////成交报告审批申请
        //        //if (applyType == WF_CONTRACT_APPLY_TYPE)
        //        //{
        //        //    #region 成交报告审批
        //        //    originatorName = fd.GetFieldValue("OriginatorName");
        //        //    oNewProcessInstance.DataFields["OriginatorName"].Value = fd.GetFieldValue("OriginatorName");
        //        //    oNewProcessInstance.DataFields["ApplyID"].Value = fd.GetFieldValue("ApplyID");
        //        //    oNewProcessInstance.DataFields["ContractID"].Value = fd.GetFieldValue("ContractID");
        //        //    oNewProcessInstance.DataFields["DeptID"].Value = fd.GetFieldValue("DeptID");
        //        //    oNewProcessInstance.DataFields["Trade"].Value = fd.GetFieldValue("Trade");
        //        //    oNewProcessInstance.DataFields["ContractReportNo"].Value = fd.GetFieldValue("ContractReportNo");
        //        //    oNewProcessInstance.DataFields["OriginatorJobName"].Value = fd.GetFieldValue("OriginatorJobName");
        //        //    oNewProcessInstance.DataFields["DeptName"].Value = fd.GetFieldValue("DeptName");
        //        //    oNewProcessInstance.DataFields["ContractPrice"].Value = fd.GetFieldValue("ContractPrice");
        //        //    oNewProcessInstance.DataFields["ContractEmpName"].Value = fd.GetFieldValue("ContractEmpName");
        //        //    oNewProcessInstance.DataFields["ContractDeptName"].Value = fd.GetFieldValue("ContractDeptName");
        //        //    oNewProcessInstance.DataFields["ContractDeptID"].Value = fd.GetFieldValue("ContractDeptID");
        //        //    oNewProcessInstance.DataFields["OriginatorMail"].Value = fd.GetFieldValue("OriginatorMail");
        //        //    oNewProcessInstance.DataFields["IsNormal"].Value = fd.GetFieldValue("IsNormal");
        //        //    oNewProcessInstance.DataFields["ReportType"].Value = fd.GetFieldValue("ReportType");
        //        //    oNewProcessInstance.DataFields["IsExistsAssistantRegionManager"].Value = fd.GetFieldValue("IsExistsAssistantRegionManager");
        //        //    opNo = "005.001.OP01";
        //        //    content = "成交报告编号为" + fd.GetFieldValue("ContractReportNo");
        //        //    //folio = (fd.GetFieldValue("IsExistArea") == "True"?"[" + fd.GetFieldValue("AreaName") + "]":"") + "[" + fd.GetFieldValue("ContractDeptName") + "][" + originatorName + "]的[" + applyName + "][" + fd.GetFieldValue("ContractReportNo") + "][" + customerTitle + fd.GetFieldValue("CustomerName") + "，" + ownerTitle + fd.GetFieldValue("OwnerName") + "]" ;
        //        //    folio = "[" + fd.GetFieldValue("ContractDeptName") + "][" + originatorName + "]的[" + applyName + "][" + fd.GetFieldValue("ContractReportNo") + "][" + fd.GetFieldValue("PropertyName") + "]";
        //        //    #endregion
        //        //}
        //        //else if (applyType == WF_MORTAGECONTRACT_APPLY_TYPE)
        //        //{
        //        //    #region 产权成交报告审批
        //        //    originatorName = fd.GetFieldValue("OriginatorName");
        //        //    oNewProcessInstance.DataFields["OriginatorName"].Value = fd.GetFieldValue("OriginatorName");
        //        //    oNewProcessInstance.DataFields["ApplyID"].Value = fd.GetFieldValue("ApplyID");
        //        //    oNewProcessInstance.DataFields["ContractID"].Value = fd.GetFieldValue("ContractID");
        //        //    oNewProcessInstance.DataFields["DeptID"].Value = fd.GetFieldValue("DeptID");
        //        //    oNewProcessInstance.DataFields["Trade"].Value = fd.GetFieldValue("Trade");
        //        //    oNewProcessInstance.DataFields["ContractReportNo"].Value = fd.GetFieldValue("ContractReportNo");
        //        //    oNewProcessInstance.DataFields["OriginatorJobName"].Value = fd.GetFieldValue("OriginatorJobName");
        //        //    oNewProcessInstance.DataFields["DeptName"].Value = fd.GetFieldValue("DeptName");
        //        //    oNewProcessInstance.DataFields["ContractPrice"].Value = fd.GetFieldValue("ContractPrice");
        //        //    oNewProcessInstance.DataFields["ContractEmpName"].Value = fd.GetFieldValue("ContractEmpName");
        //        //    oNewProcessInstance.DataFields["ContractDeptName"].Value = fd.GetFieldValue("ContractDeptName");
        //        //    oNewProcessInstance.DataFields["ContractDeptID"].Value = fd.GetFieldValue("ContractDeptID");
        //        //    oNewProcessInstance.DataFields["OriginatorMail"].Value = fd.GetFieldValue("OriginatorMail");
        //        //    oNewProcessInstance.DataFields["IsNormal"].Value = fd.GetFieldValue("IsNormal");
        //        //    oNewProcessInstance.DataFields["ReportType"].Value = fd.GetFieldValue("ReportType");
        //        //    oNewProcessInstance.DataFields["IsExistsAssistantRegionManager"].Value = fd.GetFieldValue("IsExistsAssistantRegionManager");
        //        //    opNo = "005.001.OP01";
        //        //    content = "成交报告编号为" + fd.GetFieldValue("ContractReportNo");
        //        //    //folio = (fd.GetFieldValue("IsExistArea") == "True"?"[" + fd.GetFieldValue("AreaName") + "]":"") + "[" + fd.GetFieldValue("ContractDeptName") + "][" + originatorName + "]的[" + applyName + "][" + fd.GetFieldValue("ContractReportNo") + "][" + customerTitle + fd.GetFieldValue("CustomerName") + "，" + ownerTitle + fd.GetFieldValue("OwnerName") + "]" ;
        //        //    folio = "[" + fd.GetFieldValue("ContractDeptName") + "][" + originatorName + "]的[" + applyName + "][" + fd.GetFieldValue("ContractReportNo") + "][" + fd.GetFieldValue("PropertyName") + "]";
        //        //    #endregion
        //        //}
        //        //else if (applyType == WF_MORTAGEOUT_APPLY_TYPE)
        //        //{
        //        //    #region 成交报告按揭转出审批
        //        //    originatorName = fd.GetFieldValue("OriginatorName");
        //        //    oNewProcessInstance.DataFields["OriginatorName"].Value = fd.GetFieldValue("OriginatorName");
        //        //    oNewProcessInstance.DataFields["ApplyID"].Value = fd.GetFieldValue("ApplyID");
        //        //    oNewProcessInstance.DataFields["BizDataID"].Value = fd.GetFieldValue("BizDataID");
        //        //    oNewProcessInstance.DataFields["ContractID"].Value = fd.GetFieldValue("ContractID");
        //        //    oNewProcessInstance.DataFields["DeptID"].Value = fd.GetFieldValue("DeptID");
        //        //    oNewProcessInstance.DataFields["Trade"].Value = fd.GetFieldValue("Trade");
        //        //    oNewProcessInstance.DataFields["ContractReportNo"].Value = fd.GetFieldValue("ContractReportNo");
        //        //    oNewProcessInstance.DataFields["OriginatorJobName"].Value = fd.GetFieldValue("OriginatorJobName");
        //        //    oNewProcessInstance.DataFields["DeptName"].Value = fd.GetFieldValue("DeptName");
        //        //    oNewProcessInstance.DataFields["ContractPrice"].Value = fd.GetFieldValue("ContractPrice");
        //        //    oNewProcessInstance.DataFields["ContractEmpName"].Value = fd.GetFieldValue("ContractEmpName");
        //        //    oNewProcessInstance.DataFields["ContractDeptName"].Value = fd.GetFieldValue("ContractDeptName");
        //        //    oNewProcessInstance.DataFields["ContractDeptID"].Value = fd.GetFieldValue("ContractDeptID");
        //        //    oNewProcessInstance.DataFields["OriginatorMail"].Value = fd.GetFieldValue("OriginatorMail");
        //        //    oNewProcessInstance.DataFields["IsNormal"].Value = fd.GetFieldValue("IsNormal");
        //        //    oNewProcessInstance.DataFields["ReportType"].Value = fd.GetFieldValue("ReportType");
        //        //    oNewProcessInstance.DataFields["IsExistsAssistantRegionManager"].Value = fd.GetFieldValue("IsExistsAssistantRegionManager");
        //        //    opNo = "004.010.OP08";
        //        //    content = "成交报告编号为" + fd.GetFieldValue("ContractReportNo");
        //        //    //folio = (fd.GetFieldValue("IsExistArea") == "True"?"[" + fd.GetFieldValue("AreaName") + "]":"") + "[" + fd.GetFieldValue("ContractDeptName") + "][" + originatorName + "]的[" + applyName + "][" + fd.GetFieldValue("ContractReportNo") + "][" + customerTitle + fd.GetFieldValue("CustomerName") + "，" + ownerTitle + fd.GetFieldValue("OwnerName") + "]" ;
        //        //    folio = "[" + fd.GetFieldValue("ContractDeptName") + "][" + originatorName + "]的[" + applyName + "][" + fd.GetFieldValue("ContractReportNo") + "][" + fd.GetFieldValue("PropertyName") + "]";
        //        //    #endregion
        //        //}
        //        ////成交报告调佣申请
        //        //else if (applyType == WF_COMMISION_ADDJUST_APPLY_TYPE)
        //        //{
        //        //    #region 业绩调整
        //        //    originatorName = fd.GetFieldValue("OriginatorName");
        //        //    oNewProcessInstance.DataFields["OriginatorName"].Value = fd.GetFieldValue("OriginatorName");
        //        //    oNewProcessInstance.DataFields["ApplyID"].Value = fd.GetFieldValue("ApplyID");
        //        //    oNewProcessInstance.DataFields["AdjustID"].Value = fd.GetFieldValue("AdjustID");

        //        //    oNewProcessInstance.DataFields["ContractID"].Value = fd.GetFieldValue("ContractID");
        //        //    oNewProcessInstance.DataFields["DeptID"].Value = fd.GetFieldValue("DeptID");
        //        //    oNewProcessInstance.DataFields["Trade"].Value = fd.GetFieldValue("Trade");

        //        //    oNewProcessInstance.DataFields["ContractReportNo"].Value = fd.GetFieldValue("ContractReportNo");
        //        //    oNewProcessInstance.DataFields["OriginatorJobName"].Value = fd.GetFieldValue("OriginatorJobName");
        //        //    oNewProcessInstance.DataFields["DeptName"].Value = fd.GetFieldValue("DeptName");
        //        //    oNewProcessInstance.DataFields["ContractPrice"].Value = fd.GetFieldValue("ContractPrice");
        //        //    oNewProcessInstance.DataFields["ContractEmpName"].Value = fd.GetFieldValue("ContractEmpName");
        //        //    oNewProcessInstance.DataFields["ContractDeptName"].Value = fd.GetFieldValue("ContractDeptName");
        //        //    oNewProcessInstance.DataFields["ContractDeptID"].Value = fd.GetFieldValue("ContractDeptID");

        //        //    oNewProcessInstance.DataFields["AdjustType"].Value = fd.GetFieldValue("AdjustType");
        //        //    oNewProcessInstance.DataFields["FeeTotal"].Value = fd.GetFieldValue("FeeTotal");

        //        //    oNewProcessInstance.DataFields["IsCurrentMonth"].Value = fd.GetFieldValue("IsCurrentMonth");
        //        //    oNewProcessInstance.DataFields["OriginatorMail"].Value = fd.GetFieldValue("OriginatorMail");
        //        //    oNewProcessInstance.DataFields["IsNormal"].Value = fd.GetFieldValue("IsNormal");
        //        //    oNewProcessInstance.DataFields["IsExistsAssistantRegionManager"].Value = fd.GetFieldValue("IsExistsAssistantRegionManager");
        //        //    opNo = "005.005.OP01";
        //        //    content = "成交报告编号为" + fd.GetFieldValue("ContractReportNo");
        //        //    folio = "[" + fd.GetFieldValue("ContractDeptName") + "][" + originatorName + "]的[" + applyName + "][" + fd.GetFieldValue("ContractReportNo") + "][买方" + fd.GetFieldValue("CustomerName") + "，卖方" + fd.GetFieldValue("OwnerName") + "]";
        //        //    #endregion
        //        //}
        //        ////放款申请
        //        //else if (applyType == WF_PAYMENT_APPLY_TYPE)
        //        //{
        //        //    #region 放款
        //        //    string totalMoney = "0", contractID = "";

        //        //    BusinessEntiry cashbe = new BusinessEntiry(dataManager, "FIN_PaymentApply", "PaymentID");
        //        //    if (!cashbe.Open(string.Format(" PaymentID=(Select BizDataID From WF_ApplyInstance Where ApplyID ='{0}')", applyID)))
        //        //    {
        //        //        throw new Exception("找不到放款申请信息！");
        //        //    }
        //        //    else
        //        //    {
        //        //        totalMoney = cashbe.GetPropertyValue("PaymentMoney").ToString();
        //        //        contractID = cashbe.GetPropertyValue("ContractID");
        //        //    }

        //        //    string contractNo = CentaUtil.GetPropertyValueByKeyValue(dataManager, "VW_CT_ContractReport", "ReportNo", "ContractID", contractID);
        //        //    string property = CentaUtil.GetPropertyValueByKeyValue(dataManager, "VW_CT_ContractReport", "PropertyName", "ContractID", contractID);


        //        //    originatorName = fd.GetFieldValue("OriginatorName");
        //        //    oNewProcessInstance.DataFields["OriginatorName"].Value = fd.GetFieldValue("OriginatorName");
        //        //    oNewProcessInstance.DataFields["OriginatorJobName"].Value = fd.GetFieldValue("OriginatorJobName");
        //        //    oNewProcessInstance.DataFields["OriginatorMail"].Value = fd.GetFieldValue("OriginatorMail");

        //        //    oNewProcessInstance.DataFields["ApplyID"].Value = fd.GetFieldValue("ApplyID");
        //        //    oNewProcessInstance.DataFields["BizDataID"].Value = fd.GetFieldValue("BizDataID");
        //        //    oNewProcessInstance.DataFields["DeptID"].Value = fd.GetFieldValue("DeptID");
        //        //    oNewProcessInstance.DataFields["DeptName"].Value = fd.GetFieldValue("DeptName");
        //        //    oNewProcessInstance.DataFields["ContractID"].Value = fd.GetFieldValue("ContractID");
        //        //    oNewProcessInstance.DataFields["ContractDeptID"].Value = fd.GetFieldValue("ContractDeptID");
        //        //    oNewProcessInstance.DataFields["ContractDeptName"].Value = fd.GetFieldValue("ContractDeptName");
        //        //    oNewProcessInstance.DataFields["ContractReportNo"].Value = fd.GetFieldValue("ContractReportNo");
        //        //    oNewProcessInstance.DataFields["Trade"].Value = fd.GetFieldValue("Trade");

        //        //    oNewProcessInstance.DataFields["TotalMoney"].Value = fd.GetFieldValue("TotalMoney");
        //        //    oNewProcessInstance.DataFields["IsExistsAssistantRegionManager"].Value = fd.GetFieldValue("IsExistsAssistantRegionManager");
        //        //    opNo = "005.004.OP01";

        //        //    //folio =  "[" + fd.GetFieldValue("DeptName") + "][" + originatorName + "]的[" + applyName + "](总金额:" + totalMoney + ",加快费:" + quickMoney +")";
        //        //    folio = "[" + fd.GetFieldValue("DeptName") + "][" + originatorName + "]的[" + applyName + "]([" + contractNo + "][" + property + "],金额:" + totalMoney + ")";

        //        //    #endregion
        //        //}
        //        ////订转代

        //        //else if (applyType == WF_FORWARD_APPLY_TYPE)
        //        //{
        //        //    #region 定转佣

        //        //    string totalMoney = "0", contractID = "";

        //        //    BusinessEntiry cashbe = new BusinessEntiry(dataManager, "FIN_PaymentApply", "PaymentID");
        //        //    if (!cashbe.Open(string.Format(" PaymentID=(Select BizDataID From WF_ApplyInstance Where ApplyID ='{0}')", applyID)))
        //        //    {
        //        //        throw new Exception("找不到放款申请信息！");
        //        //    }
        //        //    else
        //        //    {
        //        //        totalMoney = cashbe.GetPropertyValue("PaymentMoney").ToString();
        //        //        contractID = cashbe.GetPropertyValue("ContractID");
        //        //    }

        //        //    string contractNo = CentaUtil.GetPropertyValueByKeyValue(dataManager, "VW_CT_ContractReport", "ReportNo", "ContractID", contractID);
        //        //    string property = CentaUtil.GetPropertyValueByKeyValue(dataManager, "VW_CT_ContractReport", "PropertyName", "ContractID", contractID);


        //        //    originatorName = fd.GetFieldValue("OriginatorName");
        //        //    oNewProcessInstance.DataFields["OriginatorName"].Value = fd.GetFieldValue("OriginatorName");
        //        //    oNewProcessInstance.DataFields["OriginatorJobName"].Value = fd.GetFieldValue("OriginatorJobName");
        //        //    oNewProcessInstance.DataFields["OriginatorMail"].Value = fd.GetFieldValue("OriginatorMail");

        //        //    oNewProcessInstance.DataFields["ApplyID"].Value = fd.GetFieldValue("ApplyID");
        //        //    oNewProcessInstance.DataFields["BizDataID"].Value = fd.GetFieldValue("BizDataID");
        //        //    oNewProcessInstance.DataFields["DeptID"].Value = fd.GetFieldValue("DeptID");
        //        //    oNewProcessInstance.DataFields["DeptName"].Value = fd.GetFieldValue("DeptName");
        //        //    oNewProcessInstance.DataFields["ContractID"].Value = fd.GetFieldValue("ContractID");
        //        //    oNewProcessInstance.DataFields["ContractDeptID"].Value = fd.GetFieldValue("ContractDeptID");
        //        //    oNewProcessInstance.DataFields["ContractDeptName"].Value = fd.GetFieldValue("ContractDeptName");
        //        //    oNewProcessInstance.DataFields["ContractReportNo"].Value = fd.GetFieldValue("ContractReportNo");
        //        //    oNewProcessInstance.DataFields["Trade"].Value = fd.GetFieldValue("Trade");

        //        //    oNewProcessInstance.DataFields["TotalMoney"].Value = fd.GetFieldValue("TotalMoney");
        //        //    oNewProcessInstance.DataFields["IsExistsAssistantRegionManager"].Value = fd.GetFieldValue("IsExistsAssistantRegionManager");
        //        //    opNo = "005.004.OP01";

        //        //    //folio =  "[" + fd.GetFieldValue("DeptName") + "][" + originatorName + "]的[" + applyName + "](总金额:" + totalMoney + ",加快费:" + quickMoney +")";
        //        //    folio = "[" + fd.GetFieldValue("DeptName") + "][" + originatorName + "]的[" + applyName + "]([" + contractNo + "][" + property + "],金额:" + totalMoney + ")";

        //        //    #endregion 定转佣

        //        //}
        //        ////发票申请
        //        //else if (applyType == WF_INVOICE_APPLY_TYPE)
        //        //{
        //        //    #region 发票申请
        //        //    originatorName = fd.GetFieldValue("OriginatorName");
        //        //    oNewProcessInstance.DataFields["OriginatorName"].Value = fd.GetFieldValue("OriginatorName");
        //        //    oNewProcessInstance.DataFields["ContractID"].Value = fd.GetFieldValue("ContractID");
        //        //    oNewProcessInstance.DataFields["ApplyID"].Value = fd.GetFieldValue("ApplyID");
        //        //    oNewProcessInstance.DataFields["DeptID"].Value = fd.GetFieldValue("DeptID");

        //        //    oNewProcessInstance.DataFields["ContractReportNo"].Value = fd.GetFieldValue("ContractReportNo");
        //        //    oNewProcessInstance.DataFields["OriginatorJobName"].Value = fd.GetFieldValue("OriginatorJobName");
        //        //    oNewProcessInstance.DataFields["DeptName"].Value = fd.GetFieldValue("DeptName");
        //        //    oNewProcessInstance.DataFields["ContractEmpName"].Value = fd.GetFieldValue("ContractEmpName");
        //        //    oNewProcessInstance.DataFields["ContractDeptName"].Value = fd.GetFieldValue("ContractDeptName");
        //        //    oNewProcessInstance.DataFields["ContractDeptID"].Value = fd.GetFieldValue("ContractDeptID");

        //        //    opNo = "005.006.OP01";
        //        //    content = "成交报告编号为" + fd.GetFieldValue("ContractReportNo");
        //        //    folio = (fd.GetFieldValue("IsExistArea") == "True" ? "[" + fd.GetFieldValue("AreaName") + "]" : "") + "[" + originatorName + "]的[" + applyName + "][" + fd.GetFieldValue("ContractReportNo") + "][买方" + fd.GetFieldValue("CustomerName") + "，卖方" + fd.GetFieldValue("OwnerName") + "]";
        //        //    #endregion 发票申请
        //        //}
        //        //else if (applyType == WF_PAYMENT_COMM_APPLY_TYPE)
        //        //{
        //        //    #region 退佣

        //        //    originatorName = fd.GetFieldValue("OriginatorName");
        //        //    oNewProcessInstance.DataFields["OriginatorName"].Value = fd.GetFieldValue("OriginatorName");
        //        //    oNewProcessInstance.DataFields["ApplyID"].Value = fd.GetFieldValue("ApplyID");
        //        //    oNewProcessInstance.DataFields["ContractID"].Value = fd.GetFieldValue("ContractID");
        //        //    oNewProcessInstance.DataFields["DeptID"].Value = fd.GetFieldValue("DeptID");
        //        //    oNewProcessInstance.DataFields["IsCentaChangeOwner"].Value = fd.GetFieldValue("IsCentaChangeOwner");
        //        //    oNewProcessInstance.DataFields["IsExistArea"].Value = fd.GetFieldValue("IsExistArea");
        //        //    oNewProcessInstance.DataFields["Trade"].Value = fd.GetFieldValue("Trade");
        //        //    oNewProcessInstance.DataFields["PaymentMoney"].Value = fd.GetFieldValue("PaymentMoney");
        //        //    //oNewProcessInstance.DataFields["PaymentType"].Value = fd.GetFieldValue("PaymentType");
        //        //    //oNewProcessInstance.DataFields["PaymentTypeName"].Value = fd.GetFieldValue("PaymentTypeName");

        //        //    oNewProcessInstance.DataFields["ContractReportNo"].Value = fd.GetFieldValue("ContractReportNo");
        //        //    oNewProcessInstance.DataFields["OriginatorJobName"].Value = fd.GetFieldValue("OriginatorJobName");
        //        //    oNewProcessInstance.DataFields["DeptName"].Value = fd.GetFieldValue("DeptName");
        //        //    oNewProcessInstance.DataFields["ContractPrice"].Value = fd.GetFieldValue("ContractPrice");
        //        //    oNewProcessInstance.DataFields["ContractEmpName"].Value = fd.GetFieldValue("ContractEmpName");
        //        //    oNewProcessInstance.DataFields["ContractDeptName"].Value = fd.GetFieldValue("ContractDeptName");
        //        //    oNewProcessInstance.DataFields["ContractDeptID"].Value = fd.GetFieldValue("ContractDeptID");

        //        //    opNo = "005.004.OP01";
        //        //    content = "成交报告编号为" + fd.GetFieldValue("ContractReportNo");

        //        //    applyName = "成交报告退佣";
        //        //    folio = (fd.GetFieldValue("IsExistArea") == "True" ? "[" + fd.GetFieldValue("AreaName") + "]" : "") + "[" + fd.GetFieldValue("ContractDeptName") + "][" + originatorName + "]的[" + applyName + "][" + fd.GetFieldValue("ContractReportNo") + "][买方" + fd.GetFieldValue("CustomerName") + "，卖方" + fd.GetFieldValue("OwnerName") + "]";
        //        //    #endregion
        //        //}
        //        //else if (applyType == WF_COMPLAINCASE_APPLY_TYPE)
        //        //{
        //        //    #region 投诉事件陈述

        //        //    originatorName = fd.GetFieldValue("OriginatorName");
        //        //    oNewProcessInstance.DataFields["OriginatorName"].Value = fd.GetFieldValue("OriginatorName");
        //        //    oNewProcessInstance.DataFields["ApplyID"].Value = fd.GetFieldValue("ApplyID");
        //        //    oNewProcessInstance.DataFields["CaseID"].Value = fd.GetFieldValue("CaseID");
        //        //    oNewProcessInstance.DataFields["ContractID"].Value = fd.GetFieldValue("ContractID");
        //        //    oNewProcessInstance.DataFields["DeptID"].Value = fd.GetFieldValue("DeptID");

        //        //    oNewProcessInstance.DataFields["ContractReportNo"].Value = fd.GetFieldValue("ContractReportNo");
        //        //    oNewProcessInstance.DataFields["OriginatorJobName"].Value = fd.GetFieldValue("OriginatorJobName");
        //        //    oNewProcessInstance.DataFields["DeptName"].Value = fd.GetFieldValue("DeptName");
        //        //    oNewProcessInstance.DataFields["ContractEmpName"].Value = fd.GetFieldValue("ContractEmpName");
        //        //    oNewProcessInstance.DataFields["ContractDeptName"].Value = fd.GetFieldValue("ContractDeptName");
        //        //    oNewProcessInstance.DataFields["ContractDeptID"].Value = fd.GetFieldValue("ContractDeptID");

        //        //    opNo = "005.009.OP01";
        //        //    content = "成交报告编号为" + fd.GetFieldValue("ContractReportNo");

        //        //    applyName = "投诉事件陈述";
        //        //    folio = "[" + fd.GetFieldValue("CustomerName") + "]的" + applyName + "[" + fd.GetFieldValue("CaseNo") + "]";
        //        //    #endregion
        //        //}
        //        //else if (applyType == WF_PURSUE_APPLY_TYPE)
        //        //{
        //        //    #region 成交报告追佣

        //        //    originatorName = fd.GetFieldValue("OriginatorName");
        //        //    oNewProcessInstance.DataFields["OriginatorName"].Value = fd.GetFieldValue("OriginatorName");
        //        //    oNewProcessInstance.DataFields["ApplyID"].Value = fd.GetFieldValue("ApplyID");
        //        //    //oNewProcessInstance.DataFields["PersueID"].Value = fd.GetFieldValue("PersueID");
        //        //    oNewProcessInstance.DataFields["ContractID"].Value = fd.GetFieldValue("ContractID");
        //        //    oNewProcessInstance.DataFields["DeptID"].Value = fd.GetFieldValue("DeptID");

        //        //    //oNewProcessInstance.DataFields["Trade"].Value = fd.GetFieldValue("Trade");
        //        //    oNewProcessInstance.DataFields["ContractReportNo"].Value = fd.GetFieldValue("ContractReportNo");
        //        //    oNewProcessInstance.DataFields["OriginatorJobName"].Value = fd.GetFieldValue("OriginatorJobName");
        //        //    oNewProcessInstance.DataFields["DeptName"].Value = fd.GetFieldValue("DeptName");
        //        //    oNewProcessInstance.DataFields["ContractEmpName"].Value = fd.GetFieldValue("ContractEmpName");
        //        //    oNewProcessInstance.DataFields["ContractDeptName"].Value = fd.GetFieldValue("ContractDeptName");
        //        //    oNewProcessInstance.DataFields["ContractDeptID"].Value = fd.GetFieldValue("ContractDeptID");
        //        //    oNewProcessInstance.DataFields["LawAssistant"].Value = fd.GetFieldValue("LawAssistant");
        //        //    oNewProcessInstance.DataFields["ReasonID"].Value = fd.GetFieldValue("ReasonID");

        //        //    opNo = "005.010.OP01";
        //        //    content = "成交报告编号为[" + fd.GetFieldValue("ContractReportNo") + "]的";

        //        //    if (fd.GetFieldValue("ReasonID") == "6")
        //        //    {
        //        //        applyName = "追佣审批";
        //        //    }
        //        //    else if (fd.GetFieldValue("ReasonID") == "20")
        //        //    {
        //        //        applyName = "账龄详细情况说明";
        //        //    }
        //        //    else
        //        //    {
        //        //        applyName = "帐龄确认";
        //        //    }
        //        //    folio = content + "的" + applyName;				// + "[" + fd.GetFieldValue("CaseNo") + "]";
        //        //    #endregion
        //        //}

        //        //else if (applyType == WF_BROKAGEBACK_APPLY_TYPE)
        //        //{
        //        //    #region 返利审批
        //        //    originatorName = fd.GetFieldValue("OriginatorName");
        //        //    oNewProcessInstance.DataFields["OriginatorName"].Value = fd.GetFieldValue("OriginatorName");
        //        //    oNewProcessInstance.DataFields["ApplyID"].Value = fd.GetFieldValue("ApplyID");
        //        //    oNewProcessInstance.DataFields["DeptID"].Value = fd.GetFieldValue("DeptID");
        //        //    oNewProcessInstance.DataFields["OriginatorJobName"].Value = fd.GetFieldValue("OriginatorJobName");
        //        //    oNewProcessInstance.DataFields["DeptName"].Value = fd.GetFieldValue("DeptName");
        //        //    oNewProcessInstance.DataFields["ContractDeptID"].Value = fd.GetFieldValue("ContractDeptID");
        //        //    oNewProcessInstance.DataFields["BackType"].Value = fd.GetFieldValue("BackType");
        //        //    oNewProcessInstance.DataFields["ContractDeptID"].Value = fd.GetFieldValue("ContractDeptID");
        //        //    oNewProcessInstance.DataFields["TotalMoney"].Value = fd.GetFieldValue("TotalMoney");
        //        //    opNo = "005.012.OP01";
        //        //    content = ("[" + fd.GetFieldValue("DeptName") + "]") + (fd.GetFieldValue("BackType") == "0" ? "担保公司" : "银行") + "返利申请 [总金额为：" + fd.GetFieldValue("TotalMoney") + "]";
        //        //    folio = "[" + fd.GetFieldValue("ContractDeptName") + "][" + originatorName + "]的[" + applyName + "申请][总金额为：" + fd.GetFieldValue("TotalMoney") + "]";
        //        //    #endregion 返利审批
        //        //}

        //        //else if (applyType == WF_COMMISION_ALLOCATE_APPLY_TYPE)
        //        //{
        //        //    #region 成交报告结佣审批
        //        //    originatorName = fd.GetFieldValue("OriginatorName");
        //        //    oNewProcessInstance.DataFields["OriginatorName"].Value = fd.GetFieldValue("OriginatorName");
        //        //    oNewProcessInstance.DataFields["ApplyID"].Value = fd.GetFieldValue("ApplyID");
        //        //    oNewProcessInstance.DataFields["BizDataID"].Value = fd.GetFieldValue("BizDataID");
        //        //    oNewProcessInstance.DataFields["ContractID"].Value = fd.GetFieldValue("ContractID");
        //        //    oNewProcessInstance.DataFields["DeptID"].Value = fd.GetFieldValue("DeptID");
        //        //    oNewProcessInstance.DataFields["Trade"].Value = fd.GetFieldValue("Trade");
        //        //    oNewProcessInstance.DataFields["ContractReportNo"].Value = fd.GetFieldValue("ContractReportNo");
        //        //    oNewProcessInstance.DataFields["OriginatorJobName"].Value = fd.GetFieldValue("OriginatorJobName");
        //        //    oNewProcessInstance.DataFields["DeptName"].Value = fd.GetFieldValue("DeptName");
        //        //    oNewProcessInstance.DataFields["ContractPrice"].Value = fd.GetFieldValue("ContractPrice");
        //        //    oNewProcessInstance.DataFields["ContractEmpName"].Value = fd.GetFieldValue("ContractEmpName");
        //        //    oNewProcessInstance.DataFields["ContractDeptName"].Value = fd.GetFieldValue("ContractDeptName");
        //        //    oNewProcessInstance.DataFields["ContractDeptID"].Value = fd.GetFieldValue("ContractDeptID");
        //        //    oNewProcessInstance.DataFields["OriginatorMail"].Value = fd.GetFieldValue("OriginatorMail");
        //        //    oNewProcessInstance.DataFields["IsNormal"].Value = fd.GetFieldValue("IsNormal");
        //        //    oNewProcessInstance.DataFields["ReportType"].Value = fd.GetFieldValue("ReportType");
        //        //    oNewProcessInstance.DataFields["IsExistsAssistantRegionManager"].Value = fd.GetFieldValue("IsExistsAssistantRegionManager");
        //        //    opNo = "005.002.OP01";
        //        //    content = "成交报告编号为" + fd.GetFieldValue("ContractReportNo");
        //        //    //folio = (fd.GetFieldValue("IsExistArea") == "True"?"[" + fd.GetFieldValue("AreaName") + "]":"") + "[" + fd.GetFieldValue("ContractDeptName") + "][" + originatorName + "]的[" + applyName + "][" + fd.GetFieldValue("ContractReportNo") + "][" + customerTitle + fd.GetFieldValue("CustomerName") + "，" + ownerTitle + fd.GetFieldValue("OwnerName") + "]" ;
        //        //    folio = "[" + fd.GetFieldValue("ContractDeptName") + "][" + originatorName + "]的[" + applyName + "][" + fd.GetFieldValue("ContractReportNo") + "][" + fd.GetFieldValue("PropertyName") + "]";
        //        //    #endregion
        //        //}
        //        //else if (applyType == WF_IMPREST_APPLY_TYPE || applyType == WF_MORTAGE_IMPREST_APPLY_TYPE)
        //        //{
        //        //    #region 补足备用金申请


        //        //    string totalMoney = "0", contractID = "";
        //        //    BusinessEntiry cashbe = new BusinessEntiry(dataManager, "FIN_ImprestApply", "ItemID");
        //        //    if (!cashbe.Open(string.Format("ItemID=(Select BizDataID From WF_ApplyInstance Where ApplyID ='{0}')", applyID)))
        //        //    {
        //        //        throw new Exception("找不到补足备用金申请信息！");
        //        //    }
        //        //    else
        //        //    {
        //        //        totalMoney = cashbe.GetPropertyValue("ImprestMoney").ToString();
        //        //        contractID = cashbe.GetPropertyValue("ContractID");
        //        //    }

        //        //    string contractNo = CentaUtil.GetPropertyValueByKeyValue(dataManager, "VW_CT_ContractReport", "ReportNo", "ContractID", contractID);
        //        //    string property = CentaUtil.GetPropertyValueByKeyValue(dataManager, "VW_CT_ContractReport", "PropertyName", "ContractID", contractID);


        //        //    originatorName = fd.GetFieldValue("OriginatorName");
        //        //    oNewProcessInstance.DataFields["OriginatorName"].Value = fd.GetFieldValue("OriginatorName");
        //        //    oNewProcessInstance.DataFields["OriginatorJobName"].Value = fd.GetFieldValue("OriginatorJobName");
        //        //    oNewProcessInstance.DataFields["OriginatorMail"].Value = fd.GetFieldValue("OriginatorMail");

        //        //    oNewProcessInstance.DataFields["ApplyID"].Value = fd.GetFieldValue("ApplyID");
        //        //    oNewProcessInstance.DataFields["BizDataID"].Value = fd.GetFieldValue("BizDataID");
        //        //    oNewProcessInstance.DataFields["DeptID"].Value = fd.GetFieldValue("DeptID");
        //        //    oNewProcessInstance.DataFields["DeptName"].Value = fd.GetFieldValue("DeptName");
        //        //    oNewProcessInstance.DataFields["ContractID"].Value = fd.GetFieldValue("ContractID");
        //        //    oNewProcessInstance.DataFields["ContractDeptID"].Value = fd.GetFieldValue("ContractDeptID");
        //        //    oNewProcessInstance.DataFields["ContractDeptName"].Value = fd.GetFieldValue("ContractDeptName");
        //        //    oNewProcessInstance.DataFields["ContractReportNo"].Value = fd.GetFieldValue("ContractReportNo");
        //        //    oNewProcessInstance.DataFields["Trade"].Value = fd.GetFieldValue("Trade");

        //        //    oNewProcessInstance.DataFields["TotalMoney"].Value = fd.GetFieldValue("TotalMoney");
        //        //    oNewProcessInstance.DataFields["IsExistsAssistantRegionManager"].Value = fd.GetFieldValue("IsExistsAssistantRegionManager");
        //        //    opNo = "004.010.OP01";

        //        //    //folio =  "[" + fd.GetFieldValue("DeptName") + "][" + originatorName + "]的[" + applyName + "](总金额:" + totalMoney + ",加快费:" + quickMoney +")";
        //        //    folio = "[" + fd.GetFieldValue("DeptName") + "][" + originatorName + "]的[" + applyName + "]([" + contractNo + "][" + property + "],金额:" + totalMoney + ")";

        //        //    #endregion
        //        //}

        //        //else if (applyType == WF_INFOMODIFY_APPLY_TYPE)
        //        //{
        //        //    #region 修改委托书

        //        //    originatorName = fd.GetFieldValue("OriginatorName");
        //        //    oNewProcessInstance.DataFields["OriginatorName"].Value = fd.GetFieldValue("OriginatorName");
        //        //    oNewProcessInstance.DataFields["ContractID"].Value = fd.GetFieldValue("ContractID");
        //        //    oNewProcessInstance.DataFields["ApplyID"].Value = fd.GetFieldValue("ApplyID");
        //        //    oNewProcessInstance.DataFields["DeptID"].Value = fd.GetFieldValue("DeptID");

        //        //    oNewProcessInstance.DataFields["ContractReportNo"].Value = fd.GetFieldValue("ContractReportNo");
        //        //    oNewProcessInstance.DataFields["OriginatorJobName"].Value = fd.GetFieldValue("OriginatorJobName");
        //        //    oNewProcessInstance.DataFields["DeptName"].Value = fd.GetFieldValue("DeptName");
        //        //    oNewProcessInstance.DataFields["ContractEmpName"].Value = fd.GetFieldValue("ContractEmpName");
        //        //    oNewProcessInstance.DataFields["ContractDeptName"].Value = fd.GetFieldValue("ContractDeptName");
        //        //    oNewProcessInstance.DataFields["ContractDeptID"].Value = fd.GetFieldValue("ContractDeptID");
        //        //    oNewProcessInstance.DataFields["Reason"].Value = fd.GetFieldValue("Reason");

        //        //    opNo = "003.013.OP01";
        //        //    content = "成交报告编号为" + fd.GetFieldValue("ContractReportNo");

        //        //    folio = (fd.GetFieldValue("IsExistArea") == "True" ? "[" + fd.GetFieldValue("DeptName") + "]" : "") + "[" + originatorName + "]的[" + applyName + "][" + fd.GetFieldValue("ContractReportNo") + "][" + fd.GetFieldValue("ContractNo") + "][" + fd.GetFieldValue("OldPropertyName") + "]";

        //        //    #endregion 修改委托书申请

        //        //}

        //        //Set the Process Folio 
        //        oNewProcessInstance.Folio = folio;

        //        //Plan\Start new Process Instance 
        //        oK2Connection.StartProcessInstance(oNewProcessInstance, false);

        //        //更改K2的发起人为当前用户

        //        string originator = fd.GetFieldValue("Originator");
        //        UpdateProcessOriginator(oNewProcessInstance.ID.ToString(), originator);


        //        //Close the Connection 
        //        oK2Connection.Close();

        //        //成功则将ApplyID的状态设为[已提交]、[申请中]
        //        BusinessEntiry be = new BusinessEntiry(dataManager, "WF_ApplyInstance", "ApplyID");
        //        if (be.OpenByKeyValue(applyID))
        //        {
        //            be.SetProperty("CurState", WF_INSTANCE_APPROVING_STATE);
        //            be.SetProperty("IsWFSubmit", "1");
        //            be.SetProperty("ProcInstID", oNewProcessInstance.ID.ToString());
        //            be.SetProperty("Folio", folio);
        //            be.Save(!dataManager.IsBeginTrasaction);
        //        }


        //        #region 记录日志
        //        Log log = new Log(dataManager);
        //        log.SetProperty("LogID", CentaUtil.GetNewGUID());
        //        log.SetProperty("OperateNo", opNo);
        //        log.SetProperty("OperateName", "");//Operate.GetOperateContentByNo(opNo, dataManager));
        //        log.SetProperty("OpContent", content);
        //        log.SetProperty("OpTable", "WF_ApplyInstance");
        //        log.SetProperty("KeyID", applyID);
        //        if (page != null)
        //        {
        //            log.SetProperty("DeptID", page.Session["DeptID"].ToString());
        //            log.SetProperty("EmpID", page.Session["EmpID"].ToString());
        //            log.SetProperty("ClientIP", page.Request.UserHostAddress);
        //        }
        //        log.Save(!dataManager.IsBeginTrasaction);
        //        #endregion

        //        return true;
        //    }
        //    catch (Exception ex)
        //    {
        //        throw ex;
        //    }
        //    finally
        //    {
        //        oK2Connection.Close();
        //    }

        //}

        #endregion

        #region ===StartNewProcess===
        public static string GetK2ApplyTypeNameByType(WF.DAL.WFDBDataContext dataContext, string GetApplyTypeID)
        {
            WF_ApplyType bo = new WF_ApplyType(dataContext);
            var o = bo.GetById(GetApplyTypeID);
            return o.K2WorkflowName;// "深圳职员入职审批";
        }
        /// <summary>
        /// 启动新流程

        /// </summary>
        /// <param name="dataManager"></param>
        /// <param name="empID">发起人ID</param>
        /// <param name="applyID">申请单ID</param>
        /// <param name="applyType">流程类型</param>
        /// <returns></returns>
        public static bool StartProcessInstance(WF.DAL.WFDBDataContext dataContext, object newEntity, WF_ApplyInstanceEntity applyInstanceEntity, UserProfile userProfile)
        {
            SourceCode.Workflow.Client.ProcessInstance oNewProcessInstance;
            Connection oK2Connection = GetK2Connection();

            //取K2流程名

            string k2WorkFlowName = GetK2ApplyTypeNameByType(dataContext, applyInstanceEntity.ApplyTypeID);

            try
            {
                //Create New Process Instance 
                oNewProcessInstance = oK2Connection.CreateProcessInstance(k2WorkFlowName);

                //设置K2 datafield
                //DepartmentAdjustApplyEntity bizDeptEntity;
                KQApplyEntity bizEntity;
                string originatorName = ""; //流程发起人姓名

                string originator = "";
                string folio = "";  //流程标题名称
                //日志记录用 

                //string content = "";
                //string opNo = "";
                //string applyName = applyType; 

                originatorName = userProfile.Empname;
                originator = userProfile.LoginName;
                string[] jobLevel = { };
                switch (applyInstanceEntity.ApplyTypeName)
                {
                    #region bak
                    /*
                    case WorkFlowHelper.WF_APPLY_TYPE_DEPT_ADD:
                        bizDeptEntity = (DepartmentAdjustApplyEntity)newEntity;
                        #region 组织单元新建
                        //公有
                        oNewProcessInstance.DataFields["Originator"].Value = userProfile.LoginName;
                        oNewProcessInstance.DataFields["OriginatorName"].Value = originatorName;
                        oNewProcessInstance.DataFields["OriginatorJobName"].Value = userProfile.RoleName;
                        oNewProcessInstance.DataFields["OriginatorMail"].Value = userProfile.LoginName+"@centaline.com.cn";
                        oNewProcessInstance.DataFields["OriginatorDeptID"].Value = userProfile.DeptID;
                        oNewProcessInstance.DataFields["OriginatorDeptName"].Value = userProfile.DeptName;
                                                
                        oNewProcessInstance.DataFields["ApplyID"].Value = applyInstanceEntity.ID;
                        oNewProcessInstance.DataFields["BizDataID"].Value = applyInstanceEntity.BizDataID;

                        //私有
                        oNewProcessInstance.DataFields["BizDeptID"].Value = bizDeptEntity.CurParentID;  //bizDeptEntity.ID;
                        oNewProcessInstance.DataFields["BizDeptName"].Value = bizDeptEntity.CurParentFullName+ "/" + bizDeptEntity.DeptName;
                        oNewProcessInstance.DataFields["DeptKind"].Value = bizDeptEntity.DeptKind;
                        folio = "[" + userProfile.DeptName + " " + originatorName + "]提交的[" + applyInstanceEntity.ApplyTypeName + "]（" + bizDeptEntity.CurParentFullName + "/" + bizDeptEntity.DeptName + "）";
                        #endregion
                        break;
                    case WorkFlowHelper.WF_APPLY_TYPE_DEPT_CANCLE:
                        bizDeptEntity = (DepartmentAdjustApplyEntity)newEntity;
                        #region 组织单元撤销
                        //公有
                        oNewProcessInstance.DataFields["Originator"].Value = userProfile.LoginName;
                        oNewProcessInstance.DataFields["OriginatorName"].Value = originatorName;
                        oNewProcessInstance.DataFields["OriginatorJobName"].Value = userProfile.RoleName;
                        oNewProcessInstance.DataFields["OriginatorMail"].Value = userProfile.LoginName + "@centaline.com.cn";
                        oNewProcessInstance.DataFields["OriginatorDeptID"].Value = userProfile.DeptID;
                        oNewProcessInstance.DataFields["OriginatorDeptName"].Value = userProfile.DeptName;

                        oNewProcessInstance.DataFields["ApplyID"].Value = applyInstanceEntity.ID;
                        oNewProcessInstance.DataFields["BizDataID"].Value = applyInstanceEntity.BizDataID;

                        //私有
                        oNewProcessInstance.DataFields["BizDeptID"].Value = bizDeptEntity.ID;
                        oNewProcessInstance.DataFields["BizDeptName"].Value = bizDeptEntity.CurParentFullName + "/" + bizDeptEntity.DeptName;
                        oNewProcessInstance.DataFields["DeptKind"].Value = bizDeptEntity.DeptKind;
                        folio = "[" + userProfile.DeptName + " " + originatorName + "]提交的[" + applyInstanceEntity.ApplyTypeName + "]（" + bizDeptEntity.CurParentFullName + "/" + bizDeptEntity.DeptName + "）";
                        #endregion
                        break;
                    case WorkFlowHelper.WF_APPLY_TYPE_DEPT_ADJUST:
                        bizDeptEntity = (DepartmentAdjustApplyEntity)newEntity;
                        #region 组织单元调整
                        //公有
                        oNewProcessInstance.DataFields["Originator"].Value = userProfile.LoginName;
                        oNewProcessInstance.DataFields["OriginatorName"].Value = originatorName;
                        oNewProcessInstance.DataFields["OriginatorJobName"].Value = userProfile.RoleName;
                        oNewProcessInstance.DataFields["OriginatorMail"].Value = userProfile.LoginName + "@centaline.com.cn";
                        oNewProcessInstance.DataFields["OriginatorDeptID"].Value = userProfile.DeptID;
                        oNewProcessInstance.DataFields["OriginatorDeptName"].Value = userProfile.DeptName;

                        oNewProcessInstance.DataFields["ApplyID"].Value = applyInstanceEntity.ID;
                        oNewProcessInstance.DataFields["BizDataID"].Value = applyInstanceEntity.BizDataID;

                        //私有
                        oNewProcessInstance.DataFields["BizDeptID"].Value = bizDeptEntity.ID;
                        oNewProcessInstance.DataFields["BizDeptName"].Value = bizDeptEntity.CurParentFullName + "/" + bizDeptEntity.DeptName;
                        oNewProcessInstance.DataFields["DeptKind"].Value = bizDeptEntity.DeptKind;
                        folio = "[" + userProfile.DeptName + " " + originatorName + "]提交的[" + applyInstanceEntity.ApplyTypeName + "]（" + bizDeptEntity.CurParentFullName + "/" + bizDeptEntity.DeptName + "）";
                        #endregion
                        break;
                    case WorkFlowHelper.WF_APPLY_TYPE_EMP_JOIN:
                        bizEmpEntity = (EmployeeAdjustApplyEntity)newEntity;
                        #region 职员入职
                        //公有
                        oNewProcessInstance.DataFields["Originator"].Value = userProfile.LoginName;
                        oNewProcessInstance.DataFields["OriginatorName"].Value = originatorName;
                        oNewProcessInstance.DataFields["OriginatorJobName"].Value = userProfile.RoleName;
                        oNewProcessInstance.DataFields["OriginatorMail"].Value = userProfile.LoginName+"@centaline.com.cn";
                        oNewProcessInstance.DataFields["OriginatorDeptID"].Value = userProfile.DeptID;
                        oNewProcessInstance.DataFields["OriginatorDeptName"].Value = userProfile.DeptName;
                                                
                        oNewProcessInstance.DataFields["ApplyID"].Value = applyInstanceEntity.ID;
                        oNewProcessInstance.DataFields["BizDataID"].Value = applyInstanceEntity.BizDataID;

                        //私有
                        oNewProcessInstance.DataFields["BizDeptID"].Value = bizEmpEntity.CurDeptID;
                        oNewProcessInstance.DataFields["BizDeptName"].Value = bizEmpEntity.CurDeptFullName;
                        oNewProcessInstance.DataFields["DeptKind"].Value = bizEmpEntity.DeptKind;
                        oNewProcessInstance.DataFields["BizEmpID"].Value = "";
                        oNewProcessInstance.DataFields["BizEmpName"].Value = bizEmpEntity.Name;
                        oNewProcessInstance.DataFields["CurAuditorPositionID"].Value = bizEmpEntity.CurPositionID;//初始化，用它找上级

                        oNewProcessInstance.DataFields["BizEmpPositionID"].Value = bizEmpEntity.CurPositionID;
                        jobLevel=  bizEmpEntity.PreJobLevel.Split('-');
                        oNewProcessInstance.DataFields["JobLevel"].Value = jobLevel[0];
                        
                        folio = "[" + userProfile.DeptName + " " + originatorName + "]提交的" + applyInstanceEntity.ApplyTypeName + "](" + bizEmpEntity.Name + "/" + bizEmpEntity.EmpCode + ")";
                        #endregion
                        break;
                    case WorkFlowHelper.WF_APPLY_TYPE_EMP_PASS:
                        bizEmpEntity = (EmployeeAdjustApplyEntity)newEntity;
                        #region 职员转正
                        //公有
                        oNewProcessInstance.DataFields["Originator"].Value = userProfile.LoginName;
                        oNewProcessInstance.DataFields["OriginatorName"].Value = originatorName;
                        oNewProcessInstance.DataFields["OriginatorJobName"].Value = userProfile.RoleName;
                        oNewProcessInstance.DataFields["OriginatorMail"].Value = userProfile.LoginName + "@centaline.com.cn";
                        oNewProcessInstance.DataFields["OriginatorDeptID"].Value = userProfile.DeptID;
                        oNewProcessInstance.DataFields["OriginatorDeptName"].Value = userProfile.DeptName;

                        oNewProcessInstance.DataFields["ApplyID"].Value = applyInstanceEntity.ID;
                        oNewProcessInstance.DataFields["BizDataID"].Value = applyInstanceEntity.BizDataID;

                        //私有
                        oNewProcessInstance.DataFields["BizDeptID"].Value = bizEmpEntity.CurDeptID;
                        oNewProcessInstance.DataFields["BizDeptName"].Value = bizEmpEntity.CurDeptFullName;
                        oNewProcessInstance.DataFields["DeptKind"].Value = bizEmpEntity.DeptKind;
                        oNewProcessInstance.DataFields["BizEmpID"].Value = bizEmpEntity.EmpID;
                        oNewProcessInstance.DataFields["BizEmpName"].Value = bizEmpEntity.Name;
                        oNewProcessInstance.DataFields["CurAuditorPositionID"].Value = bizEmpEntity.CurPositionID;    //初始化，用它找上级

                        oNewProcessInstance.DataFields["BizEmpPositionID"].Value = bizEmpEntity.CurPositionID;
                        jobLevel=  bizEmpEntity.PreJobLevel.Split('-');
                        oNewProcessInstance.DataFields["JobLevel"].Value = jobLevel[0];
                        folio = "[" + userProfile.DeptName + " " + originatorName + "]提交的" + applyInstanceEntity.ApplyTypeName + "](" + bizEmpEntity.Name + "/" + bizEmpEntity.EmpCode + ")";
                        #endregion
                        break;
                    case WorkFlowHelper.WF_APPLY_TYPE_EMP_ADJUST:
                        bizEmpEntity = (EmployeeAdjustApplyEntity)newEntity;
                        #region 职员异动
                        //公有
                        oNewProcessInstance.DataFields["Originator"].Value = userProfile.LoginName;
                        oNewProcessInstance.DataFields["OriginatorName"].Value = originatorName;
                        oNewProcessInstance.DataFields["OriginatorJobName"].Value = userProfile.RoleName;
                        oNewProcessInstance.DataFields["OriginatorMail"].Value = userProfile.LoginName + "@centaline.com.cn";
                        oNewProcessInstance.DataFields["OriginatorDeptID"].Value = userProfile.DeptID;
                        oNewProcessInstance.DataFields["OriginatorDeptName"].Value = userProfile.DeptName;
                        oNewProcessInstance.DataFields["ApplyID"].Value = applyInstanceEntity.ID;
                        oNewProcessInstance.DataFields["BizDataID"].Value = applyInstanceEntity.BizDataID;

                        //私有
                        oNewProcessInstance.DataFields["BizDeptID"].Value = bizEmpEntity.CurDeptID;
                        oNewProcessInstance.DataFields["BizDeptName"].Value = bizEmpEntity.CurDeptFullName;
                        oNewProcessInstance.DataFields["DeptKind"].Value = bizEmpEntity.DeptKind;
                        oNewProcessInstance.DataFields["BizEmpID"].Value = bizEmpEntity.EmpID;
                        oNewProcessInstance.DataFields["BizEmpName"].Value = bizEmpEntity.Name;
                        oNewProcessInstance.DataFields["CurAuditorPositionID"].Value = bizEmpEntity.CurPositionID;//初始化，用它找上级


                        oNewProcessInstance.DataFields["PreBizEmpPositionID"].Value = bizEmpEntity.PrePositionID;
                        oNewProcessInstance.DataFields["BizEmpPositionID"].Value = bizEmpEntity.CurPositionID;
                        jobLevel=  bizEmpEntity.PreJobLevel.Split('-');
                        oNewProcessInstance.DataFields["JobLevel"].Value = jobLevel[0];
                        oNewProcessInstance.DataFields["AdjustTypeID"].Value = bizEmpEntity.AdjustTypeID;
                        if (bizEmpEntity.AdjustTypeID == "3")
                        {
                            oNewProcessInstance.DataFields["PreBizEmpPositionID"].Value = bizEmpEntity.PrePositionID;
                        }
                        folio = "[" + userProfile.DeptName + " " + originatorName + "]提交的" + applyInstanceEntity.ApplyTypeName + "](" + bizEmpEntity.Name + "/" + bizEmpEntity.EmpCode + ")";
                        #endregion
                        break;
                    case WorkFlowHelper.WF_APPLY_TYPE_EMP_DIMISSION:
                        bizEmpEntity = (EmployeeAdjustApplyEntity)newEntity;
                        #region 职员离职
                        //公有
                        oNewProcessInstance.DataFields["Originator"].Value = userProfile.LoginName;
                        oNewProcessInstance.DataFields["OriginatorName"].Value = originatorName;
                        oNewProcessInstance.DataFields["OriginatorJobName"].Value = userProfile.RoleName;
                        oNewProcessInstance.DataFields["OriginatorMail"].Value = userProfile.LoginName + "@centaline.com.cn";
                        oNewProcessInstance.DataFields["OriginatorDeptID"].Value = userProfile.DeptID;
                        oNewProcessInstance.DataFields["OriginatorDeptName"].Value = userProfile.DeptName;

                        oNewProcessInstance.DataFields["ApplyID"].Value = applyInstanceEntity.ID;
                        oNewProcessInstance.DataFields["BizDataID"].Value = applyInstanceEntity.BizDataID;

                        //私有
                        oNewProcessInstance.DataFields["BizDeptID"].Value = bizEmpEntity.CurDeptID;
                        oNewProcessInstance.DataFields["BizDeptName"].Value = bizEmpEntity.CurDeptPath;
                        oNewProcessInstance.DataFields["DeptKind"].Value = bizEmpEntity.DeptKind;
                        oNewProcessInstance.DataFields["BizEmpID"].Value = bizEmpEntity.EmpID;
                        oNewProcessInstance.DataFields["BizEmpName"].Value = bizEmpEntity.Name;
                        oNewProcessInstance.DataFields["CurAuditorPositionID"].Value = bizEmpEntity.CurPositionID;    //初始化，用它找上级                       
                        oNewProcessInstance.DataFields["BizEmpPositionID"].Value = bizEmpEntity.CurPositionID;
                        jobLevel=  bizEmpEntity.PreJobLevel.Split('-');
                        oNewProcessInstance.DataFields["JobLevel"].Value = jobLevel[0];
                        folio = "[" + userProfile.DeptName + " " + originatorName + "]提交的" + applyInstanceEntity.ApplyTypeName + "](" + bizEmpEntity.Name + "/" + bizEmpEntity.EmpCode + ")";
                        #endregion
                        break;
                    */
                    #endregion
                    case WorkFlowHelper.WF_APPLY_TYPE_KQAPPLY:
                        bizEntity = (KQApplyEntity)newEntity;
                        #region 假期申请
                        //公有

                        //私有
                        oNewProcessInstance.DataFields["ApplyorAccount"].Value = bizEntity.ApplyAccount;
                        oNewProcessInstance.DataFields["ProvePersonAccount"].Value = bizEntity.ProvePersonAccount;
                        oNewProcessInstance.DataFields["FlowID"].Value = bizEntity.ID;
                        oNewProcessInstance.DataFields["RegisterName"].Value = bizEntity.ApplicantName;
                        oNewProcessInstance.DataFields["RegisterDate"].Value = bizEntity.ApplyRegisterDate;
                        oNewProcessInstance.DataFields["DatetimeFrom"].Value = bizEntity.DateTimeFrom;
                        oNewProcessInstance.DataFields["DatetimeTo"].Value = bizEntity.DateTimeTo;
                        if (bizEntity.HolidayTypeCode == "")
                            throw new BusinessException("假期类型对应的流程类型没有找到，请重新选择请假类型！");//假期类型对应的流程类型没有找到，
                        oNewProcessInstance.DataFields["BillTypeCode"].Value = bizEntity.HolidayTypeCode;
                        oNewProcessInstance.DataFields["BillTypeSubCode"].Value = bizEntity.HolidayTypeSubCode;
                        oNewProcessInstance.DataFields["ApplyHours"].Value = bizEntity.ApplyHours;
                        oNewProcessInstance.DataFields["AuditorPositionID"].Value = bizEntity.AuditorPositionID;
                        oNewProcessInstance.DataFields["ApplyDays"].Value = bizEntity.ApplyDays;
                        oNewProcessInstance.DataFields["ApplyReason"].Value = bizEntity.ApplyReason;
                        oNewProcessInstance.DataFields["ApplyID"].Value = applyInstanceEntity.ID;
                        oNewProcessInstance.DataFields["OriginatorMail"].Value = bizEntity.Email;
                        oNewProcessInstance.DataFields["EmpLevel"].Value = bizEntity.EmpLevel;
                        oNewProcessInstance.DataFields["Holiday_Identify"].Value = bizEntity.HolidayIdentify;
                        oNewProcessInstance.DataFields["DeptCode"].Value = bizEntity.DeptCode;

                        #endregion
                        if (bizEntity.HoliDayTypeName == "")
                            throw new BusinessException("假期类型丢失，请重新选择请假类型！");
                        folio = "[" + bizEntity.ApplicantName + "]申请的 [" + bizEntity.HoliDayTypeName + "]";
                        break;
                }
                //Set the Process Folio 
                oNewProcessInstance.Folio = folio;

                //Plan\Start new Process Instance 
                oK2Connection.StartProcessInstance(oNewProcessInstance, false);

                //更改K2的发起人为当前用户                
                //UpdateProcessOriginator(oNewProcessInstance.ID.ToString(), originator);

                //Close the Connection 
                oK2Connection.Close();

                //将ApplyID的状态设为[已提交]
                WorkFlowHelper.UpdateWorkFlowInstance(dataContext, applyInstanceEntity.ID, 1, oNewProcessInstance.ID, folio, 0, WorkFlowHelper.WF_INSTANCE_APPROVING_STATE);

                #region 记录日志
                //Log log = new Log(dataManager);
                //log.SetProperty("LogID", CentaUtil.GetNewGUID());
                //log.SetProperty("OperateNo", opNo);
                //log.SetProperty("OperateName", "");//Operate.GetOperateContentByNo(opNo, dataManager));
                //log.SetProperty("OpContent", content);
                //log.SetProperty("OpTable", "WF_ApplyInstance");
                //log.SetProperty("KeyID", applyID);
                //if (page != null)
                //{
                //    log.SetProperty("DeptID", page.Session["DeptID"].ToString());
                //    log.SetProperty("EmpID", page.Session["EmpID"].ToString());
                //    log.SetProperty("ClientIP", page.Request.UserHostAddress);
                //}
                //log.Save(!dataManager.IsBeginTrasaction);
                #endregion

                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                oK2Connection.Close();
            }
        }
        #endregion

        #region 从K2后台数据库更改发起人
        private static void UpdateProcessOriginator(string procInstID, string originator)
        {
            if (int.Parse(procInstID) < 1)
            {
                throw new Exception("流程实例ID有误码!");
            }

            DataManager k2DataManager = new DataManager();
            string k2DBConnString = System.Configuration.ConfigurationManager.AppSettings["K2DBConnectionString"];
            string k2LogDBConnString = System.Configuration.ConfigurationManager.AppSettings["K2LogDBConnectionString"];
            try
            {
                string sql = String.Format(" Update _ProcInst Set Originator = 'CENTALINE\\{0}'  WHERE [ID] = {1}  ", originator, procInstID);

                k2DataManager.Open(k2DBConnString);
                k2DataManager.Execute(sql);

                k2DataManager.Close();
                k2DataManager.Open(k2LogDBConnString);
                k2DataManager.Execute(sql);

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                k2DataManager.Close();
            }
        }
        #endregion

        /// <summary>
        /// 设置成交报告标志
        /// </summary>
        /// <param name="dataManager"></param>
        /// <param name="contractID"></param>
        /// <param name="flagName"></param>
        public static void EnableContractFlagByName(DataManager dataManager, string contractID, string flagName)
        {
            try
            {
                string sql = String.Format(@"UPDATE CT_Contract
					SET {1} = 1 
					FROM CT_Contract 
					WHERE ContractID = '{0}'", contractID, flagName);

                dataManager.Execute(sql);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取流程发起推送DataFields的XML
        /// </summary>
        /// <param name="dataManager"></param>
        /// <param name="empID">发起人的EmpID</param>
        /// <param name="applyID">申请单ID</param>
        /// <param name="applyType">流程类型</param>
        /// <returns></returns>
        /* 
        public static string GetDataFieldsXML(DataManager dataManager, string empID, string applyID, string applyType)
        {
            try
            {
                
                string rtn = "";
                WF.WorkFlow.User user = new WF.WorkFlow.User(dataManager);
                if (!user.OpenByKeyValue(empID))
                {
                    throw new Exception("找不到员工的信息");
                }

                BusinessEntiry contract = new BusinessEntiry(dataManager, "VW_CT_ContractReport", "ContractID");
                string bizDataID = "";
                WorkFlow.WorkflowInstance wfInst = new WorkFlow.WorkflowInstance(dataManager);
                if (wfInst.OpenByKeyValue(applyID))
                {
                    bizDataID = wfInst.GetPropertyValue("BizDataID");
                }

                //string xml = "";
                //XmlHelper helper;
                //string isExistArea;              
                //string isCentaChangeOwner = "False";
                //string areaName = "";

                switch (applyType)
                {
                    #region xml
//                    case WF_CONTRACT_APPLY_TYPE:
//                        #region 成交报告申请
//                        xml = @"<ApplyInfo>
//									<ApplyID></ApplyID>
//									<ContractID></ContractID>
//									<Originator></Originator>
//                                    <OriginatorMail></OriginatorMail>
//									<OriginatorName></OriginatorName>
//									<DeptID></DeptID>
//									<Trade></Trade>
//									<ContractReportNo></ContractReportNo>
//									<OriginatorJobName></OriginatorJobName>
//									<DeptName></DeptName>
//									<ContractPrice></ContractPrice>
//									<ContractEmpName></ContractEmpName>
//									<ContractDeptName></ContractDeptName>
//									<ContractDeptID></ContractDeptID>
//									<AreaName></AreaName>
//									<OwnerName></OwnerName>
//									<CustomerName></CustomerName>
//									<PropertyName></PropertyName>
//                                    <IsNormal></IsNormal>
//                                    <ReportType></ReportType>
//                                    <IsExistsAssistantRegionManager> </IsExistsAssistantRegionManager>
//                                </ApplyInfo>";

//                        helper = new XmlHelper(xml, "ApplyID");
//                        helper.SetElementValue("ApplyID", applyID);
//                        helper.SetElementValue("Originator", user.GetPropertyValue("ADUserID"));
//                        helper.SetElementValue("OriginatorMail", user.GetPropertyValue("Email"));
//                        helper.SetElementValue("OriginatorName", user.GetPropertyValue("EmpName"));
//                        helper.SetElementValue("DeptID", user.GetPropertyValue("DeptID"));
//                        helper.SetElementValue("OriginatorJobName", user.GetPropertyValue("Job"));
//                        helper.SetElementValue("DeptName", user.GetPropertyValue("DeptName"));

//                        //根据applyID直接去WF_ApplyInstance中找BizDataID（即ContractID）

//                        if (!contract.Open(String.Format("ContractID = (SELECT BizDataID FROM WF_ApplyInstance Where ApplyID = '{0}')", applyID)))
//                        {
//                            throw new Exception("找不到成交报告的相关信息");
//                        }

//                        helper.SetElementValue("ContractID", contract.GetPropertyValue("ContractID"));
//                        helper.SetElementValue("Trade", contract.GetPropertyValue("Trade"));
//                        helper.SetElementValue("ContractReportNo", contract.GetPropertyValue("ReportNo"));
//                        helper.SetElementValue("ContractPrice", contract.GetPropertyValue("Price"));
//                        helper.SetElementValue("ContractEmpName", contract.GetPropertyValue("EmpName"));
//                        helper.SetElementValue("ContractDeptName", contract.GetPropertyValue("DeptName"));
//                        helper.SetElementValue("ContractDeptID", contract.GetPropertyValue("DeptID"));
//                        //areaName = BaseInfo.Department.GetParentDeptName(dataManager, contract.GetPropertyValue("DeptID"), "2");
//                        //helper.SetElementValue("AreaName", areaName);
//                        helper.SetElementValue("OwnerName", contract.GetPropertyValue("Owner"));
//                        helper.SetElementValue("CustomerName", contract.GetPropertyValue("Customer"));
//                        helper.SetElementValue("PropertyName", contract.GetPropertyValue("PropertyName"));
//                        helper.SetElementValue("IsNormal", contract.GetPropertyValue("IsNormal"));
//                        helper.SetElementValue("ReportType", contract.GetPropertyValue("ReportType"));
//                        helper.SetElementValue("IsExistsAssistantRegionManager",CheckExistsAssistantRegionManager(dataManager, contract.GetPropertyValue("DeptID")));
//                        rtn = helper.GetXml();
//                        break;
//                        #endregion 成交报告申请

//                    case WF_MORTAGECONTRACT_APPLY_TYPE:
//                        #region 产权成交报告申请
//                        xml = @"<ApplyInfo>
//									<ApplyID></ApplyID>
//									<ContractID></ContractID>
//									<Originator></Originator>
//                                    <OriginatorMail></OriginatorMail>
//									<OriginatorName></OriginatorName>
//									<DeptID></DeptID>
//									<Trade></Trade>
//									<ContractReportNo></ContractReportNo>
//									<OriginatorJobName></OriginatorJobName>
//									<DeptName></DeptName>
//									<ContractPrice></ContractPrice>
//									<ContractEmpName></ContractEmpName>
//									<ContractDeptName></ContractDeptName>
//									<ContractDeptID></ContractDeptID>
//									<AreaName></AreaName>
//									<OwnerName></OwnerName>
//									<CustomerName></CustomerName>
//									<PropertyName></PropertyName>
//                                    <IsNormal></IsNormal>
//                                    <ReportType></ReportType>
//                                    <IsExistsAssistantRegionManager> </IsExistsAssistantRegionManager>
//                                </ApplyInfo>";

//                        helper = new XmlHelper(xml, "ApplyID");
//                        helper.SetElementValue("ApplyID", applyID);
//                        helper.SetElementValue("Originator", user.GetPropertyValue("ADUserID"));
//                        helper.SetElementValue("OriginatorMail", user.GetPropertyValue("Email"));
//                        helper.SetElementValue("OriginatorName", user.GetPropertyValue("EmpName"));
//                        helper.SetElementValue("DeptID", user.GetPropertyValue("DeptID"));
//                        helper.SetElementValue("OriginatorJobName", user.GetPropertyValue("Job"));
//                        helper.SetElementValue("DeptName", user.GetPropertyValue("DeptName"));

//                        //根据applyID直接去WF_ApplyInstance中找BizDataID（即ContractID）

//                        if (!contract.Open(String.Format("ContractID = (SELECT BizDataID FROM WF_ApplyInstance Where ApplyID = '{0}')", applyID)))
//                        {
//                            throw new Exception("找不到成交报告的相关信息");
//                        }

//                        helper.SetElementValue("ContractID", contract.GetPropertyValue("ContractID"));
//                        helper.SetElementValue("Trade", contract.GetPropertyValue("Trade"));
//                        helper.SetElementValue("ContractReportNo", contract.GetPropertyValue("ReportNo"));
//                        helper.SetElementValue("ContractPrice", contract.GetPropertyValue("Price"));
//                        helper.SetElementValue("ContractEmpName", contract.GetPropertyValue("EmpName"));
//                        helper.SetElementValue("ContractDeptName", contract.GetPropertyValue("DeptName"));
//                        helper.SetElementValue("ContractDeptID", contract.GetPropertyValue("DeptID"));
//                        //areaName = BaseInfo.Department.GetParentDeptName(dataManager, contract.GetPropertyValue("DeptID"), "2");
//                        //helper.SetElementValue("AreaName", areaName);
//                        helper.SetElementValue("OwnerName", contract.GetPropertyValue("Owner"));
//                        helper.SetElementValue("CustomerName", contract.GetPropertyValue("Customer"));
//                        helper.SetElementValue("PropertyName", contract.GetPropertyValue("PropertyName"));
//                        helper.SetElementValue("IsNormal", contract.GetPropertyValue("IsNormal"));
//                        helper.SetElementValue("ReportType", contract.GetPropertyValue("ReportType"));
//                        helper.SetElementValue("IsExistsAssistantRegionManager", CheckExistsAssistantRegionManager(dataManager, contract.GetPropertyValue("DeptID")));
                      
//                        rtn = helper.GetXml();
//                        break;
//                        #endregion 产权成交报告申请
                  
//                    case WF_COMMISION_ADDJUST_APPLY_TYPE:
//                        #region 业绩调整申请
//                        xml = @"<ApplyInfo>
//									<ApplyID></ApplyID>
//									<ContractID></ContractID>
//									<Originator></Originator>
//									<OriginatorName></OriginatorName>
//                                    <OriginatorMail></OriginatorMail>
//									<DeptID></DeptID>
//        							<Trade></Trade>
//									<ContractReportNo></ContractReportNo>
//									<OriginatorJobName></OriginatorJobName>
//									<DeptName></DeptName>
//									<ContractPrice></ContractPrice>
//									<ContractEmpName></ContractEmpName>
//									<ContractDeptName></ContractDeptName>
//									<ContractDeptID></ContractDeptID>
//									<IsCurrentMonth></IsCurrentMonth>
//                                    <AdjustType></AdjustType>
//                                
//                                    <FeeOwner></FeeOwner>
//                                    <FeeCustomer></FeeCustomer>
//                                    <FeeTotal></FeeTotal> 
//                                    <AdjustID></AdjustID> 
//									<AreaName></AreaName>
//									<OwnerName></OwnerName>
//									<CustomerName></CustomerName>
//                                    <IsNormal></IsNormal>
//                                    <IsExistsAssistantRegionManager> </IsExistsAssistantRegionManager>
//
//								</ApplyInfo>";
                        
//                        helper = new XmlHelper(xml, "ApplyID");
//                        helper.SetElementValue("ApplyID", applyID);
//                        helper.SetElementValue("Originator", user.GetPropertyValue("aduserid"));
//                        helper.SetElementValue("OriginatorName", user.GetPropertyValue("EmpName"));
//                        helper.SetElementValue("OriginatorMail", user.GetPropertyValue("Email"));
//                        helper.SetElementValue("DeptID", user.GetPropertyValue("DeptID"));
//                        helper.SetElementValue("OriginatorJobName", user.GetPropertyValue("Job"));
                     
//                        helper.SetElementValue("DeptName", user.GetPropertyValue("DeptName"));
//                        //helper.SetElementValue("AreaName" ,areaName);

//                        //根据applyID，先去WF_ApplyInstance中找BizDataID（即AdjustID），再根据调佣报告找ContractID
//                        if (!contract.Open(String.Format("ContractID = (SELECT ContractID From CT_CommisionAdjust where AdjustID = (SELECT BizDataID FROM WF_ApplyInstance Where ApplyID = '{0}'))", applyID)))
//                        {
//                            throw new Exception("找不到成交报告的相关信息");
//                        }

//                        helper.SetElementValue("AdjustID", bizDataID);
//                        helper.SetElementValue("ContractID", contract.GetPropertyValue("ContractID"));
//                        helper.SetElementValue("Trade", contract.GetPropertyValue("Trade"));
//                        helper.SetElementValue("ContractReportNo", contract.GetPropertyValue("ReportNo"));
//                        helper.SetElementValue("ContractPrice", contract.GetPropertyValue("Price"));
//                        helper.SetElementValue("ContractEmpName", contract.GetPropertyValue("EmpName"));
//                        helper.SetElementValue("ContractDeptName", contract.GetPropertyValue("DeptName"));
//                        helper.SetElementValue("ContractDeptID", contract.GetPropertyValue("DeptID"));
                                                
//                        areaName = "";//BusinessObject.Department.GetParentDeptName(dataManager, contract.GetPropertyValue("DeptID"), "2");
//                        helper.SetElementValue("AreaName", areaName);
//                        helper.SetElementValue("OwnerName", contract.GetPropertyValue("Owner"));
//                        helper.SetElementValue("CustomerName", contract.GetPropertyValue("Customer"));

//                        BusinessEntiry adjust = new BusinessEntiry(dataManager, "VW_CT_CommisionAdjust", "AdjustID");
//                        if (!adjust.Open(String.Format("AdjustID = '{0}'", bizDataID)))
//                        {
//                            throw new Exception("找不到业绩调整申请表的相关信息");
//                        }
                       
//                        helper.SetElementValue("IsCurrentMonth", adjust.GetPropertyValue("IsCurrentMonth"));
                                              
//                        helper.SetElementValue("AdjustType", adjust.GetPropertyValue("AdjustType"));//调佣类型
//                        helper.SetElementValue("FeeOwner", adjust.GetPropertyValue("FeeOwner"));    //业主调佣金额
//                        helper.SetElementValue("FeeCustomer", adjust.GetPropertyValue("FeeCustomer"));//客户调佣金额
//                        string feeTotal = (decimal.Parse(adjust.GetPropertyValue("CustomerFee").ToString()) +
//                                          decimal.Parse(adjust.GetPropertyValue("OwnerFee").ToString())).ToString();
                        

//                        helper.SetElementValue("FeeTotal", feeTotal);
//                        helper.SetElementValue("IsNormal", adjust.GetPropertyValue("IsNormal"));
//                        helper.SetElementValue("IsExistsAssistantRegionManager", CheckExistsAssistantRegionManager(dataManager, contract.GetPropertyValue("DeptID")));
                      
//                        rtn = helper.GetXml();
//                        break;
//                        #endregion 业绩调整申请

//                    case WF_MORTAGEOUT_APPLY_TYPE:
//                        #region 按揭转出申请
//                        xml = @"<ApplyInfo>
//									<ApplyID></ApplyID>
//									<ContractID></ContractID>
//                                    <BizDataID></BizDataID>
//									<Originator></Originator>
//                                    <OriginatorMail></OriginatorMail>
//									<OriginatorName></OriginatorName>
//									<DeptID></DeptID>
//									<Trade></Trade>
//									<ContractReportNo></ContractReportNo>
//									<OriginatorJobName></OriginatorJobName>
//									<DeptName></DeptName>
//									<ContractPrice></ContractPrice>
//									<ContractEmpName></ContractEmpName>
//									<ContractDeptName></ContractDeptName>
//									<ContractDeptID></ContractDeptID>
//									<AreaName></AreaName>
//									<OwnerName></OwnerName>
//									<CustomerName></CustomerName>
//									<PropertyName></PropertyName>
//                                    <IsNormal></IsNormal>
//                                    <ReportType></ReportType>
//                                    <IsExistsAssistantRegionManager> </IsExistsAssistantRegionManager>
//                                </ApplyInfo>";

//                        helper = new XmlHelper(xml, "ApplyID");
//                        helper.SetElementValue("ApplyID", applyID);
//                        helper.SetElementValue("Originator", user.GetPropertyValue("ADUserID"));
//                        helper.SetElementValue("OriginatorMail", user.GetPropertyValue("Email"));
//                        helper.SetElementValue("OriginatorName", user.GetPropertyValue("EmpName"));
//                        helper.SetElementValue("DeptID", user.GetPropertyValue("DeptID"));
//                        helper.SetElementValue("OriginatorJobName", user.GetPropertyValue("Job"));
//                        helper.SetElementValue("DeptName", user.GetPropertyValue("DeptName"));

//                        //根据applyID直接去WF_ApplyInstance中找BizDataID（即ContractID）

//                        if (!contract.Open(String.Format("ContractID = (Select ContractID From CT_ContractMortageOut Where ItemID=(SELECT BizDataID FROM WF_ApplyInstance Where ApplyID = '{0}'))", applyID)))
//                        {
//                            throw new Exception("找不到成交报告的相关信息");
//                        }
//                        helper.SetElementValue("BizDataID", bizDataID);
//                        helper.SetElementValue("ContractID", contract.GetPropertyValue("ContractID"));
//                        helper.SetElementValue("Trade", contract.GetPropertyValue("Trade"));
//                        helper.SetElementValue("ContractReportNo", contract.GetPropertyValue("ReportNo"));
//                        helper.SetElementValue("ContractPrice", contract.GetPropertyValue("Price"));
//                        helper.SetElementValue("ContractEmpName", contract.GetPropertyValue("EmpName"));
//                        helper.SetElementValue("ContractDeptName", contract.GetPropertyValue("DeptName"));
//                        helper.SetElementValue("ContractDeptID", contract.GetPropertyValue("DeptID"));
//                        //areaName = BaseInfo.Department.GetParentDeptName(dataManager, contract.GetPropertyValue("DeptID"), "2");
//                        //helper.SetElementValue("AreaName", areaName);
//                        helper.SetElementValue("OwnerName", contract.GetPropertyValue("Owner"));
//                        helper.SetElementValue("CustomerName", contract.GetPropertyValue("Customer"));
//                        helper.SetElementValue("PropertyName", contract.GetPropertyValue("PropertyName"));
//                        helper.SetElementValue("IsNormal", contract.GetPropertyValue("IsNormal"));
//                        helper.SetElementValue("ReportType", contract.GetPropertyValue("ReportType"));
//                        helper.SetElementValue("IsExistsAssistantRegionManager", CheckExistsAssistantRegionManager(dataManager, contract.GetPropertyValue("DeptID")));

//                        rtn = helper.GetXml();
//                        break;
//                        #endregion 产权成交报告申请

//                    case WF_IMPREST_APPLY_TYPE:
//                    case WF_MORTAGE_IMPREST_APPLY_TYPE:
//                        #region 补足备用金申请

//                        xml = @"<ApplyInfo>
//									<ApplyID></ApplyID>
//                                    <BizDataID></BizDataID>  
//                                    
//									<DeptID></DeptID>
//									<DeptName></DeptName>
//									<Originator></Originator>
//									<OriginatorName></OriginatorName>
//									<OriginatorJobName></OriginatorJobName>
//                                    <OriginatorMail></OriginatorMail>
//                                    <ContractID></ContractID>
//                                    <ContractReportNo></ContractReportNo>
//                                  	<ContractDeptName></ContractDeptName>
//									<ContractDeptID></ContractDeptID>
//									<TotalMoney></TotalMoney>
//                                    <Trade></Trade>
//                                    <IsExistsAssistantRegionManager> </IsExistsAssistantRegionManager>
//
//								</ApplyInfo>";

//                        if (!contract.Open(String.Format("ContractID = (SELECT ContractID From FIN_ImprestApply where ItemID = (SELECT BizDataID FROM WF_ApplyInstance Where ApplyID = '{0}'))", applyID)))
//                        {
//                            throw new Exception("找不到成交报告的相关信息");
//                        }
                                          
//                        helper = new XmlHelper(xml, "ApplyID");
//                        helper.SetElementValue("ContractID", contract.GetPropertyValue("ContractID"));
//                        helper.SetElementValue("ContractReportNo", contract.GetPropertyValue("ReportNo"));
//                        helper.SetElementValue("Trade", contract.GetPropertyValue("Trade"));
//                        helper.SetElementValue("ApplyID", applyID);
//                        helper.SetElementValue("Originator", user.GetPropertyValue("aduserid"));
//                        helper.SetElementValue("OriginatorName", user.GetPropertyValue("EmpName"));
//                        helper.SetElementValue("OriginatorJobName", user.GetPropertyValue("Job"));
//                        helper.SetElementValue("OriginatorMail", user.GetPropertyValue("Email"));
//                        helper.SetElementValue("BizDataID", bizDataID);
//                        string contractDeptName = "";
//                        string contractDeptID = GetBackupDeptInfo(dataManager, applyID, out contractDeptName);
//                        helper.SetElementValue("DeptID", contractDeptID);
//                        helper.SetElementValue("ContractDeptID", contractDeptID);
//                        helper.SetElementValue("ContractDeptName", contractDeptName);
//                        helper.SetElementValue("DeptName", contractDeptName);
//                        helper.SetElementValue("TotalMoney", GetImprestTotalMoney(dataManager, applyID));
//                        helper.SetElementValue("IsExistsAssistantRegionManager", CheckExistsAssistantRegionManager(dataManager, contract.GetPropertyValue("DeptID")));
                      
//                        rtn = helper.GetXml();
//                        break;
//                        #endregion

                   
//                    case WF_PAYMENT_APPLY_TYPE:
//                    case WF_FORWARD_APPLY_TYPE:
//                        #region 放款申请
//                        xml = @"<ApplyInfo>
//									<ApplyID></ApplyID>
//                                    <BizDataID></BizDataID>  
//									<DeptID></DeptID>
//									<DeptName></DeptName>
//									<Originator></Originator>
//									<OriginatorName></OriginatorName>
//									<OriginatorJobName></OriginatorJobName>
//                                    <OriginatorMail></OriginatorMail>
//                                    <ContractID></ContractID>
//                                    <ContractReportNo></ContractReportNo>
//                                  	<ContractDeptName></ContractDeptName>
//									<ContractDeptID></ContractDeptID>
//									<TotalMoney></TotalMoney>
//                                    <Trade></Trade>
//                                    <IsExistsAssistantRegionManager> </IsExistsAssistantRegionManager>
//
//								</ApplyInfo>";

//                        if (!contract.Open(String.Format("ContractID = (SELECT ContractID From FIN_PaymentApply where PaymentID = (SELECT BizDataID FROM WF_ApplyInstance Where ApplyID = '{0}'))", applyID)))
//                        {
//                            throw new Exception("找不到成交报告的相关信息");
//                        }

//                        helper = new XmlHelper(xml, "ApplyID");
//                        helper.SetElementValue("ContractID", contract.GetPropertyValue("ContractID"));
//                        helper.SetElementValue("ContractReportNo", contract.GetPropertyValue("ReportNo"));
//                        helper.SetElementValue("Trade", contract.GetPropertyValue("Trade"));
//                        helper.SetElementValue("ApplyID", applyID);
//                        helper.SetElementValue("Originator", user.GetPropertyValue("aduserid"));
//                        helper.SetElementValue("OriginatorName", user.GetPropertyValue("EmpName"));
//                        helper.SetElementValue("OriginatorJobName", user.GetPropertyValue("Job"));
//                        helper.SetElementValue("OriginatorMail", user.GetPropertyValue("Email"));
//                        helper.SetElementValue("BizDataID", bizDataID);
//                        string DeptName = contract.GetPropertyValue("DeptName");
//                        string DeptID = contract.GetPropertyValue("DeptID");
//                        helper.SetElementValue("DeptID", DeptID);
//                        helper.SetElementValue("ContractDeptID", DeptID);
//                        helper.SetElementValue("ContractDeptName",DeptName);
//                        helper.SetElementValue("DeptName", DeptName);
//                        helper.SetElementValue("TotalMoney", GetPaymentTotalMoney(dataManager, applyID));
//                        helper.SetElementValue("IsExistsAssistantRegionManager", CheckExistsAssistantRegionManager(dataManager, contract.GetPropertyValue("DeptID")));
                      
//                        rtn = helper.GetXml();
//                        break;
//                        #endregion 放款申请
//                    case WF_INVOICE_APPLY_TYPE:
//                        #region 发票申请
//                        xml = @"<ApplyInfo>
//									<ApplyID></ApplyID>
//									<Originator></Originator>
//									<OriginatorName></OriginatorName>
//									<OriginatorJobName></OriginatorJobName>
//									<DeptID></DeptID>
//									<DeptName></DeptName>
//									<ContractID></ContractID>
//									<ContractReportNo></ContractReportNo>
//									<ContractEmpName></ContractEmpName>
//									<ContractDeptName></ContractDeptName>
//									<ContractDeptID></ContractDeptID>
//									<IsExistArea></IsExistArea>
//									<CustomerName></CustomerName>
//									<OwnerName></OwnerName>
//									<AreaName></AreaName>
//								</ApplyInfo>";

//                        helper = new XmlHelper(xml, "ApplyID");
//                        helper.SetElementValue("ApplyID", applyID);
//                        helper.SetElementValue("Originator", user.GetPropertyValue("aduserid"));
//                        helper.SetElementValue("OriginatorName", user.GetPropertyValue("EmpName"));
//                        helper.SetElementValue("DeptID", user.GetPropertyValue("DeptID"));
//                        helper.SetElementValue("OriginatorJobName", user.GetPropertyValue("Job"));
//                        helper.SetElementValue("DeptName", user.GetPropertyValue("DeptName"));

//                        //根据applyID，先去WF_ApplyInstance中找BizDataID（即InvoiceID），再根据发票申请表找ContractID
//                        if (!contract.Open(String.Format("ContractID = (SELECT ContractID From FIN_InvoiceApply where InvoiceID = (SELECT BizDataID FROM WF_ApplyInstance Where ApplyID = '{0}'))", applyID)))
//                        {
//                            throw new Exception("找不到成交报告的相关信息");
//                        }

//                        helper.SetElementValue("ContractID", contract.GetPropertyValue("ContractID"));
//                        helper.SetElementValue("ContractReportNo", contract.GetPropertyValue("ReportNo"));
//                        helper.SetElementValue("ContractEmpName", contract.GetPropertyValue("EmpName"));
//                        helper.SetElementValue("ContractDeptName", contract.GetPropertyValue("DeptName"));
//                        helper.SetElementValue("ContractDeptID", contract.GetPropertyValue("DeptID"));

//                        helper.SetElementValue("CustomerName", contract.GetPropertyValue("Customer"));
//                        helper.SetElementValue("OwnerName", contract.GetPropertyValue("Owner"));
//                        isExistArea = IsDeptExistArea(dataManager, contract.GetPropertyValue("DeptID"), out areaName) ? "True" : "False";
//                        helper.SetElementValue("IsExistArea", isExistArea);
//                        helper.SetElementValue("AreaName", areaName);

//                        rtn = helper.GetXml();
//                        break;
//                        #endregion 发票申请

//                    case WF_COMMISION_ALLOCATE_APPLY_TYPE:
//                        #region 结佣申请
//                        xml = @"<ApplyInfo>
//									<ApplyID></ApplyID>
//									<ContractID></ContractID>
//                                    <BizDataID></BizDataID>
//									<Originator></Originator>
//                                    <OriginatorMail></OriginatorMail>
//									<OriginatorName></OriginatorName>
//									<DeptID></DeptID>
//									<Trade></Trade>
//									<ContractReportNo></ContractReportNo>
//									<OriginatorJobName></OriginatorJobName>
//									<DeptName></DeptName>
//									<ContractPrice></ContractPrice>
//									<ContractEmpName></ContractEmpName>
//									<ContractDeptName></ContractDeptName>
//									<ContractDeptID></ContractDeptID>
//									
//									<OwnerName></OwnerName>
//									<CustomerName></CustomerName>
//									<PropertyName></PropertyName>
//                                    <IsNormal></IsNormal>
//                                    <ReportType></ReportType>
//                                    <IsExistsAssistantRegionManager> </IsExistsAssistantRegionManager>
//                                </ApplyInfo>";

//                        helper = new XmlHelper(xml, "ApplyID");
//                        helper.SetElementValue("ApplyID", applyID);
//                        helper.SetElementValue("Originator", user.GetPropertyValue("ADUserID"));
//                        helper.SetElementValue("OriginatorMail", user.GetPropertyValue("Email"));
//                        helper.SetElementValue("OriginatorName", user.GetPropertyValue("EmpName"));
//                        helper.SetElementValue("DeptID", user.GetPropertyValue("DeptID"));
//                        helper.SetElementValue("OriginatorJobName", user.GetPropertyValue("Job"));
//                        helper.SetElementValue("DeptName", user.GetPropertyValue("DeptName"));

//                        //根据applyID直接去WF_ApplyInstance中找BizDataID（即ContractID）

//                        if (!contract.Open(String.Format("ContractID = (Select ContractID From FIN_CommisionAllocateApply Where ItemID=(SELECT BizDataID FROM WF_ApplyInstance Where ApplyID = '{0}'))", applyID)))
//                        {
//                            throw new Exception("找不到成交报告的相关信息");
//                        }
//                        helper.SetElementValue("BizDataID", bizDataID);
//                        helper.SetElementValue("ContractID", contract.GetPropertyValue("ContractID"));
//                        helper.SetElementValue("Trade", contract.GetPropertyValue("Trade"));
//                        helper.SetElementValue("ContractReportNo", contract.GetPropertyValue("ReportNo"));
//                        helper.SetElementValue("ContractPrice", contract.GetPropertyValue("Price"));
//                        helper.SetElementValue("ContractEmpName", contract.GetPropertyValue("EmpName"));
//                        helper.SetElementValue("ContractDeptName", contract.GetPropertyValue("DeptName"));
//                        helper.SetElementValue("ContractDeptID", contract.GetPropertyValue("DeptID"));
//                        //areaName = BaseInfo.Department.GetParentDeptName(dataManager, contract.GetPropertyValue("DeptID"), "2");
//                        //helper.SetElementValue("AreaName", areaName);
//                        helper.SetElementValue("OwnerName", contract.GetPropertyValue("Owner"));
//                        helper.SetElementValue("CustomerName", contract.GetPropertyValue("Customer"));
//                        helper.SetElementValue("PropertyName", contract.GetPropertyValue("PropertyName"));
//                        helper.SetElementValue("IsNormal", contract.GetPropertyValue("IsNormal"));
//                        helper.SetElementValue("ReportType", contract.GetPropertyValue("ReportType"));
//                        helper.SetElementValue("IsExistsAssistantRegionManager", CheckExistsAssistantRegionManager(dataManager, contract.GetPropertyValue("DeptID")));

//                        rtn = helper.GetXml();
//                        break;
//                        #endregion 结佣申请
                    #endregion
                    default:
                        break;
                }
                    
                return rtn;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        */
        #region 取得返利成交报告对佣的申请ID
        private static void GetBroakageContractInfo(DataManager dataManager, string applyID, out string allocateApplyID, out string applyType)
        {

            BusinessEntiry be = new BusinessEntiry(dataManager, "VW_WF_ApplyInstance", "ApplyID");
            if (be.OpenByKeyValue(applyID))
            {
                applyType = be.GetPropertyValue("ApplyType");
            }
            else
            {
                applyType = "";
            }

            be = new BusinessEntiry(dataManager, "VW_WF_ApplyInstance", "ApplyID");
            be.Open(String.Format(@" BizDataID =(Select AllocateID From CT_CommisionAllocateApply Where ContractID 
                                     = (Select BizDataID From WF_ApplyInstance Where ApplyID ='{0}'))", applyID));

            allocateApplyID = be.GetPropertyValue("ApplyID");
        }
        #endregion 取得返利成交报告对佣的申请ID

        /// <summary>
        /// 检查empID所在地铺是否存在二级区域

        /// </summary>
        /// <param name="dataManager"></param>
        /// <param name="empID"></param>
        /// <returns></returns>
        public static bool IsEmpExistArea(DataManager dataManager, string empID, out string areaName)
        {
            string sql = String.Format(@"SELECT d.*
				FROM F_DeptType dt INNER JOIN
					F_Department d ON dt.DeptType = d.DeptType AND 
					dt.DeptType=2 INNER JOIN
					VW_F_Employee e ON e.DeptFullCode LIKE d.DeptFullCode + '%' 
				WHERE e.EmpID = '{0}'", empID);

            SqlDataReader rs = dataManager.selectReader(sql);
            bool rtn = rs.Read();
            if (rtn)
            {
                areaName = rs["DeptName"].ToString();
            }
            else
            {
                areaName = "";
            }
            rs.Close();
            return rtn;
        }

        /// <summary>
        /// 检查分行是否存在二级区域

        /// </summary>
        /// <param name="dataManager"></param>
        /// <param name="deptID"></param>
        /// <param name="areaName"></param>
        /// <returns></returns>
        public static bool IsDeptExistArea(DataManager dataManager, string deptID, out string areaName)
        {
            string sql = String.Format(@"SELECT p.*
				FROM F_Department s INNER JOIN
					F_Department p ON s.DeptFullCode LIKE p.DeptFullCode + '%' INNER JOIN
					F_DeptType ON p.DeptType = F_DeptType.DeptType
				WHERE (F_DeptType.DeptType=2) 
					and s.DeptID = '{0}'", deptID);

            SqlDataReader rs = dataManager.selectReader(sql);
            bool rtn = rs.Read();
            if (rtn)
            {
                areaName = rs["DeptName"].ToString();
            }
            else
            {
                areaName = "";
            }
            rs.Close();
            return rtn;
        }

        /// <summary>
        /// 检查bizDataID是否已存在applyType的流程实例

        /// </summary>
        /// <param name="dataManager"></param>
        /// <param name="bizDataID"></param>
        /// <param name="applyType"></param>
        /// <returns></returns>
        public static bool IsWFInstanceExist(DataManager dataManager, string bizDataID, string applyType)
        {
            string sql = String.Format(@"SELECT *
				FROM WF_ApplyInstance INNER JOIN
					CFG_WFApplyType ON 
					WF_ApplyInstance.ApplyTypeID = CFG_WFApplyType.ApplyTypeID
				WHERE (WF_ApplyInstance.BizDataID = N'{0}') AND (CFG_WFApplyType.ApplyType = N'{1}')", bizDataID, applyType);

            SqlDataReader rs = dataManager.selectReader(sql);
            bool rtn = rs.Read();
            rs.Close();
            return rtn;
        }

        /// <summary>
        /// 根据ApplyID获取BizDataID
        /// </summary>
        /// <param name="dataManager"></param>
        /// <param name="applyID"></param>
        /// <returns></returns>
        public static string GetBizDataIDByApplyID(DataManager dataManager, string applyID)
        {
            BusinessEntiry be = new BusinessEntiry(dataManager, "VW_WF_ApplyInstance", "ApplyID");
            if (be.OpenByKeyValue(applyID))
            {
                //如果是通过返利申请生成的成交报告，
                if (1 == 1) //(be.GetPropertyValue("ApplyType") == WF_BROKAGEBACKCONTRACT_APPLY_TYPE)
                    return CentaUtil.GetPropertyValueByKeyValue(dataManager, "CT_BrokageReturn", "NewContractID", "ItemID", be.GetPropertyValue("BizDataID"));
                else
                    return be.GetPropertyValue("BizDataID");
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// 根据BizDataID获取ApplyID
        /// </summary>
        /// <param name="dataManager"></param>
        /// <param name="bizDataID"></param>
        /// <returns></returns>3
        public static string GetApplyIDByBizDataID(DataManager dataManager, string bizDataID)
        {
            BusinessEntiry be = new BusinessEntiry(dataManager, "WF_ApplyInstance", "ApplyID");
            if (be.Open(String.Format("BizDataID='{0}'", bizDataID)))
            {
                return be.GetPropertyValue("ApplyID");
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// 获取用户帐号短名称(去掉"centaline\\")
        /// </summary>
        /// <param name="adUserID">用户帐号</param>
        /// <returns></returns>
        public static string GetShortADUserID(string adUserID)
        {
            try
            {
                string result = adUserID;
                if (adUserID.Trim() != "")
                {
                    string delimStr = "\\";
                    char[] delimiter = delimStr.ToCharArray();
                    string[] split = null;
                    split = adUserID.Split(delimiter);
                    if (split.Length > 1)
                    {
                        result = split[1];
                    }
                }
                return result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取成交报告的成交部门ID
        /// </summary>
        /// <param name="dataManager"></param>
        /// <param name="contractID"></param>
        /// <returns></returns>
        public static string GetContractDeptID(DataManager dataManager, string contractID)
        {
            return "";
            //CCAILib.Contract.Contract.Contract contract = new WF.Contract.Contract.Contract(dataManager);
            //if (contract.OpenByKeyValue(contractID))
            //{
            //    return contract.GetPropertyValue("DeptID");
            //}
            //else
            //{
            //    throw new Exception("找不到相应的成交报告");
            //}
        }

        private static string GetApplyDetailCount(DataManager dataManager, string applyID)
        {
            string sql = String.Format("select count(*) from WF_ApplyInstanceDetail where ApplyID='{0}'", applyID);
            return CentaUtil.SelectScale(dataManager, sql);
        }

        public static DataSet GetDeptManagerByEmpADUserID(DataManager dataManager, string userID)
        {
            try
            {
                string sql = String.Format(@"SELECT em.*
					FROM F_Employee e INNER JOIN
						F_Employee em ON e.DeptID = em.DeptID
					WHERE (e.ADUserID = N'{0}') AND (em.IsDeptManager = 1) AND em.DelFlag = 0", WorkFlowHelper.GetShortADUserID(userID));

                DataSet ds = dataManager.SelectDataSet(sql);
                //				if(ds.Tables[0].Rows.Count == 0)
                //				{
                //					throw new Exception(String.Format("找不到[{0}]的部门负责人信息" ,userID));
                //				}
                //this.CheckExistADUserID(ds ,"部门经理");
                return ds;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static void BindLawRiskLevel(System.Web.UI.WebControls.DropDownList list)
        {
            System.Collections.ArrayList al = new System.Collections.ArrayList();
            al.Add("高");
            al.Add("中");
            al.Add("低");
            list.DataSource = al;
            list.DataBind();
        }

        /// <summary>
        /// 获取成交报告法务审核的意见及审核人，法务经理审核后发邮件通知（包含法务意见，并抄送给法务）

        /// </summary>
        /// <param name="dataManager"></param>
        /// <param name="contractID"></param>
        /// <returns></returns>
        public static DataSet GetContractLawAudit(DataManager dataManager, string contractID)
        {
            string sql = String.Format(@"SELECT top 1 WF_AuditHistory.*, WF_ApplyInstance.BizDataID
FROM WF_AuditHistory INNER JOIN
      WF_ApplyInstance ON 
      WF_AuditHistory.ApplyID = WF_ApplyInstance.ApplyID INNER JOIN
      CFG_WFApplyType ON 
      WF_ApplyInstance.ApplyTypeID = CFG_WFApplyType.ApplyTypeID
WHERE (CFG_WFApplyType.ApplyType = N'{0}') AND (WF_ApplyInstance.BizDataID = N'{1}') AND (WF_AuditHistory.ActivityName = N'法务审核')
ORDER BY WF_AuditHistory.ApprovalDate DESC", WF_APPLY_TYPE_DEPT_ADD, contractID);

            return CentaUtil.SelectDataSet(dataManager, sql);
        }

        #region 取得补足按揭部申请所在部门

        private static string GetTillCashDeptInfo(DataManager dataManager, string applyID, out string deptName)
        {
            string deptID = "";
            string sql = string.Format(@" Select * From VW_FIN_SupplementalTillCash Where applyID='{0}'", applyID);
            SqlDataReader rs = dataManager.selectReader(sql);
            bool rtn = rs.Read();
            if (rtn)
            {
                deptName = rs["DeptName"].ToString();
                deptID = rs["DeptID"].ToString();
            }
            else
            {
                deptName = "";
            }
            rs.Close();
            return deptID;

        }
        #endregion

        #region 取得补足备用金申请所在部门

        private static string GetBackupDeptInfo(DataManager dataManager, string applyID, out string deptName)
        {
            string deptID = "";
            string sql = string.Format(@" Select * From VW_FIN_ImprestApply Where applyID='{0}'", applyID);
            SqlDataReader rs = dataManager.selectReader(sql);
            bool rtn = rs.Read();
            if (rtn)
            {
                deptName = rs["DeptName"].ToString();
                deptID = rs["DeptID"].ToString();
            }
            else
            {
                deptName = "";
            }
            rs.Close();
            return deptID;

        }
        #endregion

        #region 补备时是否抵押放定

        private static string GetIsPayEarnest(DataManager dataManager, string applyID)
        {
            string isPayEarnest = "0";
            string sql = string.Format(@" Select IsPayEarnest From VW_FIN_SupplementalTillCash Where ApplyID ='{0}'", applyID);
            SqlDataReader rs = dataManager.selectReader(sql);
            bool rtn = rs.Read();
            if (rtn)
            {
                isPayEarnest = rs["IsPayEarnest"].ToString();

            }
            else
            {
                isPayEarnest = "0";
            }
            rs.Close();
            return isPayEarnest;
        }

        private static string GetBackupIsPayEarnest(DataManager dataManager, string applyID)
        {
            string isPayEarnest = "0";
            string sql = string.Format(@" Select IsPayEarnest From VW_FIN_ImprestApply Where ApplyID ='{0}'", applyID);
            SqlDataReader rs = dataManager.selectReader(sql);
            bool rtn = rs.Read();
            if (rtn)
            {
                isPayEarnest = rs["IsPayEarnest"].ToString();

            }
            else
            {
                isPayEarnest = "0";
            }
            rs.Close();
            return isPayEarnest;
        }
        #endregion

        #region 补足按揭部时的款项类型

        private static string GetEnvaluate(DataManager dataManager, string applyID)
        {
            string ret = "0";
            string sql = string.Format(@" Select Envaluate From VW_FIN_SupplementalTillCash Where ApplyID ='{0}'", applyID);
            SqlDataReader rs = dataManager.selectReader(sql);
            bool rtn = rs.Read();
            if (rtn)
            {
                ret = rs["Envaluate"].ToString();

            }
            else
            {
                ret = "0";
            }
            rs.Close();
            return ret;
        }
        #endregion

        #region 取得备用金用途中是否有“补足按揭部”

        private static string GetPurpose(DataManager dataManager, string applyID)
        {
            string sql = string.Format(@" If Exists(Select Purpose From FIN_SupplementalTillCashDetail Where Purpose='补足按揭部'
                                          And  SupplementalID = (Select BizDataID From WF_ApplyInstance Where ApplyID ='{0}'))
                                           Select Purpose= '补足按揭部' Else Select Purpose='补备'", applyID);
            return CentaUtil.SelectScale(dataManager, sql);
        }
        #endregion

        #region 取得补足备用金用途

        private static string GetBackupPurpose(DataManager dataManager, string applyID)
        {
            string sql = string.Format(@" Select Purpose From FIN_ImprestApply Where ItemID=(Select BizDataID From WF_ApplyInstance Where ApplyID='{0}')", applyID);
            return CentaUtil.SelectScale(dataManager, sql);
        }
        #endregion

        #region 取得补足备用金申请表的加快费、总费用

        private static string GetQuickMoney(DataManager dataManager, string applyID)
        {
            string sql = String.Format(@"Select IsNull(Sum(a.TotalMoney),0) As QuickMoney From FIN_SupplementalTillCashDetail a 
                                         Inner Join FIN_SupplementalTillCash b on a.SupplementalID= b.SupplementalID
                                         Where a.Purpose='加快费' and b.SupplementalID = (Select BizDataID From WF_ApplyInstance Where ApplyID='{0}')", applyID);
            return CentaUtil.SelectScale(dataManager, sql);
        }

        private static string GetImprestTotalMoney(DataManager dataManager, string applyID)
        {
            string sql = String.Format(@"Select IsNull(ImprestMoney,0) As TotalMoney From FIN_ImprestApply  
                                       Where  ItemID = (Select BizDataID From WF_ApplyInstance Where ApplyID='{0}')", applyID);
            return CentaUtil.SelectScale(dataManager, sql);
        }

        private static string GetPaymentTotalMoney(DataManager dataManager, string applyID)
        {
            string sql = String.Format(@"Select IsNull(PaymentMoney,0) As TotalMoney From FIN_PaymentApply  
                                       Where  PaymentID = (Select BizDataID From WF_ApplyInstance Where ApplyID='{0}')", applyID);
            return CentaUtil.SelectScale(dataManager, sql);
        }
        private static string GetTotalMoney(DataManager dataManager, string applyID)
        {
            string sql = String.Format(@"Select IsNull(Sum(a.TotalMoney),0) As QuickMoney From FIN_SupplementalTillCashDetail a 
                                         Inner Join FIN_SupplementalTillCash b on a.SupplementalID= b.SupplementalID
                                         Where  b.SupplementalID = (Select BizDataID From WF_ApplyInstance Where ApplyID='{0}')", applyID);
            return CentaUtil.SelectScale(dataManager, sql);
        }
        #endregion

        #region 往审批历史记录表插入数据

        public static void InsertAuditHistory(DataManager dataManager, string applyID, string confirmEmpName, string confirmAduserID,
            string approvalResult, string approvalComment, string approvalDate, string activityName)
        {
            //记历史

            string sql = string.Format(@" Select top 1 approvalResult from WF_AuditHistory Where ApplyID ='{0}' and ActivityName='{1}'
                            and DomainAccount='{2}' order by ApprovalDate Desc", applyID, activityName, confirmAduserID);
            if ((CentaUtil.SelectScale(dataManager, sql) == null || CentaUtil.SelectScale(dataManager, sql) == "") || CentaUtil.SelectScale(dataManager, sql) != approvalResult)
            {
                BusinessEntiry be = new BusinessEntiry(dataManager, "WF_AuditHistory", "ItemID");
                be.SetProperty("ItemID", System.Guid.NewGuid().ToString());
                be.SetProperty("ApplyID", applyID);
                be.SetProperty("UserName", confirmEmpName);
                be.SetProperty("DomainAccount", confirmAduserID);
                be.SetProperty("ApprovalResult", approvalResult);
                be.SetProperty("ApprovalComment", approvalComment);
                be.SetProperty("ApprovalDate", approvalDate);
                be.SetProperty("ActivityName", activityName);
                be.Save(!dataManager.IsBeginTrasaction);
            }
        }
        #endregion

        #region 审批页面绑定历史审批记录
        public static void BindApprovalAuditHistory(Connection oK2Connection, string sn, System.Web.UI.WebControls.DataGrid datagrid)
        {

            SourceCode.Workflow.Client.WorklistItem worklistItem = oK2Connection.OpenWorklistItem(sn);
            if (worklistItem != null)
            {
                System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
                string srcXML = worklistItem.ProcessInstance.XmlFields["ApprovalResult"].Value;
                if (srcXML.Trim().Length > 0)
                {
                    srcXML = srcXML.Replace("<<", "&lt;&lt;");
                    srcXML = srcXML.Replace(">>", "&gt;&gt;");
                    xmlDoc.LoadXml(srcXML);
                    System.Xml.XmlNode node = xmlDoc.SelectSingleNode("Root/Approvals");
                    if (node != null)
                    {
                        System.Xml.XmlNodeReader reader = new System.Xml.XmlNodeReader(node);
                        System.Data.DataSet ds = new DataSet(); ;
                        ds.ReadXml(reader);
                        datagrid.DataSource = ds.Tables[0].DefaultView;
                        datagrid.DataBind();
                    }
                }
            }
        }

        public static void BindApprovalAuditHistory(SourceCode.Workflow.Client.WorklistItem worklistItem, System.Web.UI.WebControls.ListView gridView1)
        {
            if (worklistItem != null)
            {
                System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
                string srcXML = worklistItem.ProcessInstance.XmlFields["ApprovalResult"].Value;
                if (srcXML.Trim().Length > 0)
                {
                    srcXML = srcXML.Replace("<<", "&lt;&lt;");
                    srcXML = srcXML.Replace(">>", "&gt;&gt;");
                    xmlDoc.LoadXml(srcXML);
                    System.Xml.XmlNode node = xmlDoc.SelectSingleNode("Root/Approvals");
                    if (node != null)
                    {
                        System.Xml.XmlNodeReader reader = new System.Xml.XmlNodeReader(node);
                        System.Data.DataSet ds = new DataSet(); ;
                        ds.ReadXml(reader);
                        gridView1.DataSource = ds.Tables[0].DefaultView;
                        gridView1.DataBind();
                    }
                }
            }
        }
        #endregion 审批页面绑定历史审批记录

        #region 取得当前审批步骤的名称

        public static string GetCurrentActivityName(Connection oK2Connection, string sn)
        {
            string retValue = "";
            SourceCode.Workflow.Client.WorklistItem wli = oK2Connection.OpenWorklistItem(sn);
            if (wli != null)
            {
                retValue = wli.ActivityInstanceDestination.Name;
            }
            return retValue;
        }

        public static string GetCurrentActivityName(SourceCode.Workflow.Client.WorklistItem wli)
        {
            string retValue = "";
            if (wli != null)
            {
                retValue = wli.ActivityInstanceDestination.Name;
            }
            return retValue;
        }

        public static string GetCurrentActivityDisplayName(Connection oK2Connection, string sn)
        {
            string retValue = "";
            SourceCode.Workflow.Client.WorklistItem wli = oK2Connection.OpenWorklistItem(sn);
            if (wli != null)
            {
                retValue = wli.ActivityInstanceDestination.Description;
            }
            return retValue;
        }

        public static string GetCurrentActivityDisplayName(SourceCode.Workflow.Client.WorklistItem wli)
        {
            string retValue = "";
            if (wli != null)
            {
                retValue = wli.ActivityInstanceDestination.Description;
            }
            return retValue;
        }
        #endregion 取得当前审批步骤的名称


        #region 根据流程类型以及当前步骤绑定审批结果
        /// <summary>
        /// 根据流程类型以及当前步骤绑定审批结果
        /// </summary>
        /// <param name="radioButtonList"></param>
        /// <param name="applyType"></param>
        /// <param name="currentActivityName"></param>
        public static void BindApprovalResultRadioButtonList(RadioButtonList radioButtonList, string applyType, string currentActivityName)
        {
            radioButtonList.Items.Clear();
            currentActivityName = currentActivityName.Replace(" ", "");
            switch (applyType)
            {
                //case WF.Common.WorkFlowHelper.WF_CONTRACT_APPLY_TYPE:
                //    #region 成交报告
                //    switch (currentActivityName)
                //    {
                //        case "分行经理审核":
                //            radioButtonList.Items.Add(new ListItem("通过", "1"));
                //            radioButtonList.Items.Add(new ListItem("驳回修改", "2"));
                //            radioButtonList.SelectedValue = "1";
                //            break;

                //        case "助理区域经理审核":
                //            radioButtonList.Items.Add(new ListItem("通过", "1"));
                //            radioButtonList.Items.Add(new ListItem("驳回修改", "2"));
                //            radioButtonList.SelectedValue = "1";
                //            break;
                //        case "区域经理审核":
                //            radioButtonList.Items.Add(new ListItem("通过", "1"));
                //            radioButtonList.Items.Add(new ListItem("驳回修改", "2"));
                //            radioButtonList.SelectedValue = "1";
                //            break;

                //        case "法务专员审核":
                //            radioButtonList.Items.Add(new ListItem("打回补充资料", "3"));
                //            radioButtonList.Items.Add(new ListItem("通过", "1"));
                //            //radioButtonList.Items.Add(new ListItem("有异议", "4"));
                //            radioButtonList.SelectedValue = "1";
                //            break;

                //        case "三级市场副总经理审核":
                //        case "三级市场总经理审核":
                //            radioButtonList.Items.Add(new ListItem("驳回修改", "2"));
                //            radioButtonList.Items.Add(new ListItem("通过", "1"));
                //            radioButtonList.SelectedValue = "1";
                //            break;

                //    }
                //    #endregion
                //    break;
                //case WF.Common.WorkFlowHelper.WF_COMMISION_ALLOCATE_APPLY_TYPE:
                //    #region 成交报告结佣
                //    switch (currentActivityName)
                //    {
                //        case "产权交易部审核":
                //            radioButtonList.Items.Add(new ListItem("已过户,按揭未转出", "1"));
                //            radioButtonList.Items.Add(new ListItem("已过户,按揭转出", "-2"));
                //            radioButtonList.Items.Add(new ListItem("未过户,按揭未转出", "0"));
                //            radioButtonList.Items.Add(new ListItem("未过户,按揭转出", "-4"));

                //            radioButtonList.SelectedValue = "0";
                //            break;

                //        case "法务专员审核":

                //            radioButtonList.Items.Add(new ListItem("无风险", "1"));
                //            radioButtonList.Items.Add(new ListItem("风险等级:低", "2"));
                //            radioButtonList.Items.Add(new ListItem("风险等级:中", "3"));
                //            radioButtonList.Items.Add(new ListItem("风险等级:高", "4"));
                //            radioButtonList.SelectedValue = "2";
                //            break;

                //        case "助理区域经理审核":                         
                //        case "区域经理审核":
                //        case "区域总监审核":
                //        case "三级市场副总经理审核":
                //        case "三级市场总经理审核":
                //            radioButtonList.Items.Add(new ListItem("拒绝", "0"));
                //            radioButtonList.Items.Add(new ListItem("通过", "1"));
                //            radioButtonList.SelectedValue = "1";
                //            break;

                //    }
                //    #endregion
                //    break;
                //case WF.Common.WorkFlowHelper.WF_MORTAGEOUT_APPLY_TYPE:
                //    #region 成交报告按揭转出
                //    switch (currentActivityName)
                //    {
                //        case "产权经理审核":
                //            radioButtonList.Items.Add(new ListItem("通过(可转出)", "1"));
                //            radioButtonList.Items.Add(new ListItem("不可转出", "0"));
                //            radioButtonList.SelectedValue = "1";
                //            break;


                //        case "综合管理中心经理审核":
                //            radioButtonList.Items.Add(new ListItem("拒绝", "0"));
                //            radioButtonList.Items.Add(new ListItem("通过", "1"));
                //            radioButtonList.SelectedValue = "1";
                //            break;

                //    }
                //    #endregion
                //    break;
                //case WF.Common.WorkFlowHelper.WF_MORTAGECONTRACT_APPLY_TYPE:
                //    #region 产权成交报告
                //    switch (currentActivityName)
                //    {
                //        case "综合管理中心经理审核":
                //        case "产权交易部审核":
                //            radioButtonList.Items.Add(new ListItem("通过", "1"));
                //            radioButtonList.Items.Add(new ListItem("驳回修改", "2"));
                //            radioButtonList.SelectedValue = "1";
                //            break;          

                //        case "三级市场副总经理审核":
                //            radioButtonList.Items.Add(new ListItem("驳回修改", "2"));
                //            radioButtonList.Items.Add(new ListItem("通过", "1"));
                //            radioButtonList.SelectedValue = "1";
                //            break;

                //    }
                //    #endregion
                //    break;

                //case WF.Common.WorkFlowHelper.WF_COMMISION_ADDJUST_APPLY_TYPE:
                //    #region 调佣
                //    switch (currentActivityName)
                //    {
                //        case "分行经理审核":
                //            radioButtonList.Items.Add(new ListItem("通过", "1"));
                //            radioButtonList.Items.Add(new ListItem("驳回修改", "2"));
                //            radioButtonList.Items.Add(new ListItem("拒绝", "0"));
                //            radioButtonList.SelectedValue = "1";
                //            break;

                //        case "助理区域经理审核":
                //        case "区域经理审核":
                //        case "三级市场副总经理审核":
                //        case "三级市场总经理审核":
                //            radioButtonList.Items.Add(new ListItem("通过", "1"));
                //            radioButtonList.Items.Add(new ListItem("驳回修改", "2"));
                //            radioButtonList.Items.Add(new ListItem("拒绝", "0"));
                //            radioButtonList.SelectedValue = "1";
                //            break;


                //    }
                //    #endregion
                //    break;
                //case WF.Common.WorkFlowHelper.WF_PAYMENT_APPLY_TYPE:
                //    #region 放款
                //    switch (currentActivityName)
                //    {
                //        case "分行经理审核":
                //        case "助理区域经理审核":
                //        case "区域经理审核":
                //        case "三级市场副总经理审核":
                //        case "三级市场总经理审核":
                //            radioButtonList.Items.Add(new ListItem("拒绝", "0"));
                //            radioButtonList.Items.Add(new ListItem("通过", "1"));
                //            radioButtonList.Items.Add(new ListItem("驳回修改", "2"));
                //            radioButtonList.SelectedValue = "1";
                //            break;
                //        case "法务专员审核":
                //        case "法务经理审核":
                //            radioButtonList.Items.Add(new ListItem("拒绝", "0"));
                //            radioButtonList.Items.Add(new ListItem("通过", "1"));
                //            radioButtonList.Items.Add(new ListItem("驳回修改", "2"));
                //            radioButtonList.SelectedValue = "1";
                //            break;
                //        case "产权经理审核":
                //            radioButtonList.Items.Add(new ListItem("拒绝", "0"));
                //            radioButtonList.Items.Add(new ListItem("通过", "1"));
                //            radioButtonList.Items.Add(new ListItem("驳回修改", "2"));
                //            radioButtonList.Items.Add(new ListItem("打回补充资料", "3"));
                //            radioButtonList.SelectedValue = "1";
                //            break;
                //    }
                //    #endregion
                //    break;

                //case WF.Common.WorkFlowHelper.WF_ACCOUNTFLOWHISTORY_APPLY_TYPE:
                //    #region 收款确认
                //    switch (currentActivityName)
                //    {
                //        case "申请人修改":
                //            break;
                //        case "计佣专员审核":
                //        case "计佣会计审核":
                //        case "代收款专员审核":
                //        case "代收款会计审核":
                //            radioButtonList.Items.Add(new ListItem("通过", "1"));
                //            radioButtonList.Items.Add(new ListItem("驳回修改", "3"));
                //            radioButtonList.Items.Add(new ListItem("拒绝", "-1"));
                //            radioButtonList.SelectedValue = "1";
                //            break;
                //    }
                //    #endregion
                //    break;
                //case WF.Common.WorkFlowHelper.WF_BROKAGEBACK_APPLY_TYPE:
                //    #region 返利申请
                //    switch (currentActivityName)
                //    {
                //        case "申请人修改":
                //            break;
                //        case "财务审核":
                //            radioButtonList.Items.Add(new ListItem("通过", "1"));
                //            radioButtonList.Items.Add(new ListItem("驳回修改", "2"));
                //            //radioButtonList.Items.Add(new ListItem("拒绝", "-1"));
                //            radioButtonList.SelectedValue = "1";
                //            break;

                //    }
                //    #endregion
                //    break;
                //case WF.Common.WorkFlowHelper.WF_BROKAGEBACKCONTRACT_APPLY_TYPE:
                //    #region 返利成交报告审批
                //    switch (currentActivityName)
                //    {
                //        case "分行经理审核":
                //        case "按揭经理审核":
                //            radioButtonList.Items.Add(new ListItem("拒绝", "0"));
                //            radioButtonList.Items.Add(new ListItem("通过", "1"));
                //            radioButtonList.SelectedValue = "1";
                //            break;
                //        default:
                //            break;

                //    }
                //    #endregion
                //    break;

                //case WF.Common.WorkFlowHelper.WF_STAMP_APPLY_TYPE:
                //    #region 盖章
                //    switch (currentActivityName)
                //    {

                //        case "区域经理审核":
                //        case "区域总监审核":
                //        case "区域总经理审核":
                //        case "财务审核":
                //        case "住宅部高级秘书审核":
                //            radioButtonList.Items.Add(new ListItem("通过", "1"));
                //            radioButtonList.Items.Add(new ListItem("驳回重填", "2"));
                //            radioButtonList.Items.Add(new ListItem("拒绝", "0"));
                //            radioButtonList.SelectedValue = "1";
                //            break;
                //        case "法务初审":
                //            radioButtonList.Items.Add(new ListItem("通过", "1"));
                //            radioButtonList.Items.Add(new ListItem("驳回重填", "2"));
                //            radioButtonList.Items.Add(new ListItem("补充资料", "3"));
                //            radioButtonList.Items.Add(new ListItem("拒绝", "0"));
                //            radioButtonList.SelectedValue = "1";
                //            break;
                //        case "法务复审":
                //            radioButtonList.Items.Add(new ListItem("通过", "1"));
                //            radioButtonList.Items.Add(new ListItem("驳回重填", "2"));
                //            radioButtonList.Items.Add(new ListItem("补充资料", "3"));
                //            radioButtonList.Items.Add(new ListItem("拒绝", "0"));
                //            radioButtonList.SelectedValue = "1";
                //            break;
                //        case "分行文员检查资料":
                //        case "三级市场总经理审核":
                //            radioButtonList.Items.Add(new ListItem("通过", "1"));
                //            radioButtonList.Items.Add(new ListItem("拒绝", "0"));
                //            radioButtonList.SelectedValue = "1";
                //            break;
                //    }
                //    #endregion
                //    break;
                //case WF.Common.WorkFlowHelper.WF_IMPREST_APPLY_TYPE:
                //    #region 补足备用金

                //    switch (currentActivityName)
                //    {

                //        case "分行经理审核":
                //        case "助理区域经理审核":
                //        case "区域经理审核":
                //        case "三级市场总经理审核":
                //            radioButtonList.Items.Add(new ListItem("拒绝", "0"));
                //            radioButtonList.Items.Add(new ListItem("通过", "1"));
                //            radioButtonList.Items.Add(new ListItem("驳回修改", "2"));
                //            radioButtonList.SelectedValue = "1";
                //            break;
                //        case "法务专员审核":
                //            radioButtonList.Items.Add(new ListItem("拒绝", "0"));
                //            radioButtonList.Items.Add(new ListItem("通过", "1"));
                //            radioButtonList.Items.Add(new ListItem("驳回修改", "2"));
                //            radioButtonList.Items.Add(new ListItem("打回补充资料", "3"));
                //            radioButtonList.SelectedValue = "1";
                //            break;
                //     }
                //    #endregion
                //    break;
                //case WF.Common.WorkFlowHelper.WF_MORTAGE_IMPREST_APPLY_TYPE:
                //    #region 产权补足备用金

                //    switch (currentActivityName)
                //    {
                //        case "综合管理中心经理审核":
                //            radioButtonList.Items.Add(new ListItem("通过", "1"));
                //            radioButtonList.Items.Add(new ListItem("驳回修改", "2"));
                //            radioButtonList.SelectedValue = "1";
                //            break;

                //        case "三级市场副总经理审核":
                //            radioButtonList.Items.Add(new ListItem("驳回修改", "2"));
                //            radioButtonList.Items.Add(new ListItem("通过", "1"));
                //            radioButtonList.SelectedValue = "1";
                //            break;

                //    }
                //    #endregion
                //    break;
                //case WF.Common.WorkFlowHelper.WF_INFOMODIFY_APPLY_TYPE:
                //    #region 修改委托书

                //    switch (currentActivityName)
                //    {
                //        case "分行经理审核":
                //        case "区域经理审核":
                //        case "财务审核":
                //            radioButtonList.Items.Add(new ListItem("通过", "1"));
                //            radioButtonList.Items.Add(new ListItem("驳回重填", "2"));
                //            radioButtonList.Items.Add(new ListItem("拒绝", "0"));
                //            radioButtonList.SelectedValue = "1";
                //            break;
                //    }
                //    #endregion
                //    break;


            }
        }
        #endregion

        #region 检查WorkListItem的操作

        /// <summary>
        /// 
        /// </summary>
        /// <param name="oK2Connection"></param>
        /// <param name="sn"></param>
        /// <returns></returns>
        /*
        public static bool CheckWorkListItem(Connection oK2Connection, string sn)
        {
            try
            {
                SourceCode.Workflow.Client.WorklistItem worklistItem = oK2Connection.OpenWorklistItem(sn, "ASP",false);
                return true;
            }
            catch
            {
                return false;
            }
        }
        */

        public static bool CheckWorkListItem(Connection oK2Connection, string sn, string managedUser, string sharedUser)
        {

            try
            {
                SourceCode.Workflow.Client.WorklistItem worklistItem = GetWorkListItemBySN(oK2Connection, sn, managedUser, sharedUser);
                return true;
            }
            catch
            {
                return false;
            }
        }
        #endregion

        #region 取得流程待办事项
        public static SourceCode.Workflow.Client.WorklistItem GetWorkListItemBySN1(Connection oK2Connection, string sn)
        {
            SourceCode.Workflow.Client.WorklistItem worklistItem = oK2Connection.OpenWorklistItem(sn, "ASP");
            if (worklistItem != null)
            {
                return worklistItem;
            }
            else
            {
                return null;
            }
        }
        public static SourceCode.Workflow.Client.WorklistItem GetWorkListItemBySN(Connection oK2Connection, string sn, string managedUser, string sharedUser)
        {
            SourceCode.Workflow.Client.WorklistItem worklistItem = null;
            try
            {
                //正常的

                if ((string.IsNullOrEmpty(sharedUser)) && (managedUser == string.Empty))
                {
                    worklistItem = oK2Connection.OpenWorklistItem(sn, "ASP");
                }

                if ((!string.IsNullOrEmpty(sharedUser)) && (managedUser == string.Empty))
                {

                    worklistItem = oK2Connection.OpenSharedWorklistItem(sharedUser, managedUser, sn);

                }

                if ((string.IsNullOrEmpty(sharedUser)) && (managedUser != string.Empty))
                {
                    worklistItem = oK2Connection.OpenManagedWorklistItem(managedUser, sn);
                }

                // 检查是否为委托的

                if ((!string.IsNullOrEmpty(sharedUser)) && (managedUser != string.Empty))
                {
                    worklistItem = oK2Connection.OpenSharedWorklistItem(sharedUser, managedUser, sn);
                }
            }
            catch
            {
                worklistItem = null;
            }

            return worklistItem;

        }
        protected static SourceCode.Workflow.Client.WorklistItem GetWorkListItemBySN2(Connection oK2Connection, string sn, string managedUser, string sharedUser, bool bAlloc, bool bIgnoreStatus)
        {
            SourceCode.Workflow.Client.WorklistItem worklistItem = null;
            try
            {
                //正常的

                if ((string.IsNullOrEmpty(sharedUser)) && (managedUser == string.Empty))
                {
                    worklistItem = oK2Connection.OpenWorklistItem(sn, "ASP", bAlloc, bIgnoreStatus);
                }

                if ((!string.IsNullOrEmpty(sharedUser)) && (managedUser == string.Empty))
                {

                    worklistItem = oK2Connection.OpenSharedWorklistItem(sharedUser, managedUser, sn, "ASP", bAlloc, bIgnoreStatus);

                }

                if ((string.IsNullOrEmpty(sharedUser)) && (managedUser != string.Empty))
                {
                    worklistItem = oK2Connection.OpenManagedWorklistItem(managedUser, sn, "ASP", bAlloc, bIgnoreStatus);
                }

                // 检查是否为委托的

                if ((!string.IsNullOrEmpty(sharedUser)) && (managedUser != string.Empty))
                {
                    worklistItem = oK2Connection.OpenSharedWorklistItem(sharedUser, managedUser, sn, "ASP", bAlloc, bIgnoreStatus);
                }
            }
            catch
            {
                worklistItem = null;
            }

            return worklistItem;

        }
        #endregion

        #region 取得流程实例的DataField
        public static string GetInstanceDataFields(Connection oK2Connection, string sn, string fieldName, bool isXMLField)
        {
            string retValue = "";
            SourceCode.Workflow.Client.WorklistItem worklistItem = oK2Connection.OpenWorklistItem(sn, "ASP");
            if (worklistItem != null)
            {
                if (isXMLField)
                {
                    retValue = worklistItem.ProcessInstance.XmlFields[fieldName].Value.ToString();
                }
                else
                {
                    retValue = worklistItem.ProcessInstance.DataFields[fieldName].Value.ToString();
                }
            }

            return retValue;
        }
        public static string GetInstanceDataFields(Connection oK2Connection, string sn, string fieldName, bool isXMLField, string managedUser, string sharedUser)
        {
            string retValue = "";

            SourceCode.Workflow.Client.WorklistItem worklistItem = GetWorkListItemBySN(oK2Connection, sn, managedUser, sharedUser);
            if (worklistItem != null)
            {
                if (isXMLField)
                {
                    retValue = worklistItem.ProcessInstance.XmlFields[fieldName].Value.ToString();
                }
                else
                {
                    retValue = worklistItem.ProcessInstance.DataFields[fieldName].Value.ToString();
                }
            }

            return retValue;
        }
        public static string GetInstanceDataFields(SourceCode.Workflow.Client.WorklistItem worklistItem, string fieldName, bool isXMLField)
        {
            string retValue = "";
            if (worklistItem != null)
            {
                if (isXMLField)
                {
                    retValue = worklistItem.ProcessInstance.XmlFields[fieldName].Value.ToString();
                }
                else
                {
                    retValue = worklistItem.ProcessInstance.DataFields[fieldName].Value.ToString();
                }
            }

            return retValue;
        }
        #endregion 取得流程实例的DataField

        #region 设置流程实例的DataField
        public static void SetInstanceDataFields(Connection oK2Connection, string sn, string fieldName, string fieldValue, bool isXMLField)
        {
            string userName = oK2Connection.User.Name;
            SourceCode.Workflow.Client.WorklistItem worklistItem = oK2Connection.OpenWorklistItem(sn, "ASP");
            //转给流程管理者

            oK2Connection.RevertUser();
            worklistItem.Redirect(oK2Connection.User.Name);

            worklistItem = oK2Connection.OpenWorklistItem(sn, "ASP");
            if (worklistItem != null)
            {
                if (isXMLField)
                {
                    worklistItem.ProcessInstance.XmlFields[fieldName].Value = fieldValue;

                }
                else
                {
                    worklistItem.ProcessInstance.DataFields[fieldName].Value = fieldValue;

                }

                //更新实例的DataField值

                try
                {
                    worklistItem.ProcessInstance.Update();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    //再转回当前审批人
                    worklistItem.Redirect(userName);
                    oK2Connection.ImpersonateUser(userName);
                }
            }
        }
        public static void SetInstanceDataFields(Connection oK2Connection, string sn, string fieldName, string fieldValue, bool isXMLField, string managedUser, string sharedUser)
        {
            string userName = oK2Connection.User.Name;
            SourceCode.Workflow.Client.WorklistItem worklistItem = GetWorkListItemBySN(oK2Connection, sn, managedUser, sharedUser);
            //转给流程管理者

            oK2Connection.RevertUser();
            worklistItem.Redirect(oK2Connection.User.Name);

            worklistItem = oK2Connection.OpenWorklistItem(sn, "ASP");
            if (worklistItem != null)
            {
                if (isXMLField)
                {
                    worklistItem.ProcessInstance.XmlFields[fieldName].Value = fieldValue;

                }
                else
                {
                    worklistItem.ProcessInstance.DataFields[fieldName].Value = fieldValue;

                }

                //更新实例的DataField值

                try
                {
                    worklistItem.ProcessInstance.Update();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    //再转回当前审批人
                    worklistItem.Redirect(userName);
                    oK2Connection.ImpersonateUser(userName);
                }
            }

        }


        // 一欠更新多个dataField
        //
        public static void SetInstanceDataFields(Connection oK2Connection, string sn, List<DataFieldItemEntity> dataFieldItemEntitys)
        {
            string userName = oK2Connection.User.Name;
            SourceCode.Workflow.Client.WorklistItem worklistItem = oK2Connection.OpenWorklistItem(sn, "ASP");
            //转给流程管理者


            oK2Connection.RevertUser();
            worklistItem.Redirect(oK2Connection.User.Name);

            worklistItem = oK2Connection.OpenWorklistItem(sn, "ASP");

            if (worklistItem != null)
            {
                foreach (DataFieldItemEntity entity in dataFieldItemEntitys)
                {
                    if (entity.IsXMLField)
                    {
                        worklistItem.ProcessInstance.XmlFields[entity.FieldName].Value = entity.FieldValue;
                    }
                    else
                    {
                        worklistItem.ProcessInstance.DataFields[entity.FieldName].Value = entity.FieldValue;
                    }
                }

                //更新实例的DataField值

                try
                {
                    worklistItem.ProcessInstance.Update();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    //再转回当前审批人
                    worklistItem.Redirect(userName);
                    oK2Connection.ImpersonateUser(userName);
                }
            }
        }

        // 一欠更新多个dataField
        //
        public static void SetInstanceDataFields(Connection oK2Connection, string sn, List<DataFieldItemEntity> dataFieldItemEntitys, string managedUser, string sharedUser)
        {
            string userName = oK2Connection.User.Name;
            SourceCode.Workflow.Client.WorklistItem worklistItem = GetWorkListItemBySN(oK2Connection, sn, managedUser, sharedUser); // oK2Connection.OpenWorklistItem(sn, "ASP");
            //转给流程管理者


            oK2Connection.RevertUser();
            worklistItem.Redirect(oK2Connection.User.Name);

            worklistItem = oK2Connection.OpenWorklistItem(sn, "ASP");

            if (worklistItem != null)
            {
                foreach (DataFieldItemEntity entity in dataFieldItemEntitys)
                {
                    if (entity.IsXMLField)
                    {
                        worklistItem.ProcessInstance.XmlFields[entity.FieldName].Value = entity.FieldValue;
                    }
                    else
                    {
                        worklistItem.ProcessInstance.DataFields[entity.FieldName].Value = entity.FieldValue;
                    }
                }

                //更新实例的DataField值

                try
                {
                    worklistItem.ProcessInstance.Update();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    //再转回当前审批人
                    worklistItem.Redirect(userName);
                    oK2Connection.ImpersonateUser(userName);
                }
            }
        }

        public static void SetInstanceDataFields(SourceCode.Workflow.Client.WorklistItem worklistItem, string fieldName, string fieldValue, bool isXMLField)
        {
            if (worklistItem != null)
            {
                if (isXMLField)
                {
                    worklistItem.ProcessInstance.XmlFields[fieldName].Value = fieldValue;
                }
                else
                {
                    worklistItem.ProcessInstance.DataFields[fieldName].Value = fieldValue;
                }
            }
        }

        #endregion 设置流程实例的DataField

        #region 设置流程实例的folio
        public static void SetInstanceFolio(Connection oK2Connection, string sn, string folio)
        {
            string userName = oK2Connection.User.Name;
            SourceCode.Workflow.Client.WorklistItem worklistItem = oK2Connection.OpenWorklistItem(sn, "ASP");
            //转给流程管理者


            oK2Connection.RevertUser();
            worklistItem.Redirect(oK2Connection.User.Name);

            worklistItem = oK2Connection.OpenWorklistItem(sn, "ASP");
            if (worklistItem != null)
            {
                worklistItem.ProcessInstance.Folio = folio;
                try
                {
                    worklistItem.ProcessInstance.Update();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    //再转回当前审批人
                    worklistItem.Redirect(userName);
                    oK2Connection.ImpersonateUser(userName);
                }
            }
        }
        public static void SetInstanceFolio(Connection oK2Connection, string sn, string folio, string managedUser, string sharedUser)
        {
            string userName = oK2Connection.User.Name;
            SourceCode.Workflow.Client.WorklistItem worklistItem = GetWorkListItemBySN(oK2Connection, sn, managedUser, sharedUser); //oK2Connection.OpenWorklistItem(sn, "ASP");
            //转给流程管理者


            oK2Connection.RevertUser();
            worklistItem.Redirect(oK2Connection.User.Name);

            worklistItem = oK2Connection.OpenWorklistItem(sn, "ASP");
            if (worklistItem != null)
            {
                worklistItem.ProcessInstance.Folio = folio;
                try
                {
                    worklistItem.ProcessInstance.Update();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    //再转回当前审批人
                    worklistItem.Redirect(userName);
                    oK2Connection.ImpersonateUser(userName);
                }
            }
        }
        #endregion 设置流程实例的folio

        #region 完成当前的WorkListItem
        public static void FinishWorklistItem(SourceCode.Workflow.Client.WorklistItem wli)
        {
            foreach (SourceCode.Workflow.Client.Action action in wli.Actions)
            {
                if (action.Name == "Task Completed")
                {
                    action.Execute();
                }
            }
        }
        #endregion

        #region 窗口方法
        /// <summary>
        /// 当前审批步骤完成
        /// </summary>
        /// <param name="page"></param>
        public static void CloseApprovalWindow(System.Web.UI.Page page)
        {
            string returnValue = "true";
            page.Response.Write("<script language='javascript'>window.returnValue=\"" + returnValue + "\";</script>");
            page.Response.Write("<script language='javascript'>window.close();</script>");
            page.Response.End();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="page"></param>
        public static void ajaxCloseApprovalWindow(System.Web.UI.Control control, string returnValue)
        {
            //string returnValue = "true";
            AjaxSetWindowReturnValue(control, returnValue);
            AjaxWindowClose(control);
        }

        /// <summary>
        /// 显示信息并闭窗口
        /// </summary>
        /// <param name="page"></param>
        /// <param name="message"></param>
        public static void ShowWarningMessage(System.Web.UI.Page page, string message)
        {
            string script = "<script language='javascript'>alert('" + message + "');window.returnValue=\"true\";window.close();</script>";
            page.Response.Write(script);
            page.Response.End();
        }

        /// <summary>
        /// 关闭使用了Ajax技术的窗口
        /// </summary>
        /// <param name="control">所属对象，一般用this或this.Page或UpdatePanel的ID</param>
        public static void AjaxWindowClose(System.Web.UI.Control control)
        {
            System.Web.UI.ScriptManager.RegisterStartupScript(control, control.GetType(), "Close", "window.close();", true);

        }

        /// <summary>
        /// 从使用了Ajax技术的模态窗口返回值

        /// </summary>
        /// <param name="control">所属对象，一般为this或this.Page</param>
        /// <param name="returnValue">返回值</param>
        public static void AjaxSetWindowReturnValue(System.Web.UI.Control control, string returnValue)
        {
            string script = "window.returnValue=\"" + returnValue + "\";";
            System.Web.UI.ScriptManager.RegisterStartupScript(control, control.GetType(), "ReturnValue", script, true);

        }

        #endregion

        #region 根据旧的历史审批记录生成并设置新的历史审批记录(ApprovalResult/LastApprovalResult)

        /// <summary>
        /// 根据旧的历史审批记录生成并设置新的历史审批记录(ApprovalResult/LastApprovalResult)
        /// </summary>
        /// <param name="page">当前页面对象</param>
        /// <param name="dgApprovalResult">显示历史记录的表格对象(在提交前要把它的绑定去掉)</param>
        /// <param name="approvalResultXML">旧审批历史记录XML</param>
        /// <param name="txtLastApprovalResult">旧的最后审批历史记录文档框对象</param>
        /// <param name="comAuditResult">审批结果(同意/重填/补充资料)</param>
        /// <param name="comAuditComment">审批意见</param>
        /// <param name="currentActivityName">当前流程步骤名称</param>
        public static void SetApprovalResult(Connection oK2Connection,
            string ADUserID,
            string SN,
            string comAuditResultValue,
            string comAuditResultText,
            string comAuditComment,
            string currentActivityName)
        {
            try
            {
                //把审批意见的<>号替换掉
                comAuditComment = comAuditComment.Replace("<", "&lt;");
                comAuditComment = comAuditComment.Replace(">", "&gt;");

                string approvalResultXML = GetInstanceDataFields(oK2Connection, SN, "ApprovalResult", true);
                string lastApprovalResultXML = GetInstanceDataFields(oK2Connection, SN, "LastApprovalResult", true);
                //如果是第一次。xml是空的。则自动加上节点<?xml version="1.0" encoding="UTF-8" ?><Root><Approvals></Approvals></Root>
                if (approvalResultXML.Trim() == "")
                {
                    approvalResultXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><Root><Approvals></Approvals></Root>";
                }
                if (lastApprovalResultXML.Trim() == "")
                {
                    lastApprovalResultXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><Root><Approvals></Approvals></Root>";
                }

                string adUserID = "CENTALINE\\" + ADUserID; //page.User.Identity.Name.ToString();
                adUserID = WorkFlowHelper.GetShortADUserID(adUserID);
                string empName = GetEmpNameByADUserID(adUserID);

                SourceCode.Workflow.Client.WorklistItem curWorkListItem = oK2Connection.OpenWorklistItem(SN);
                if (currentActivityName != null)
                {
                    XMLApproval xmlApproval = new XMLApproval();

                    //增加一个审批记录


                    xmlApproval.LoadFromXML(approvalResultXML);
                    xmlApproval.AddApproval(empName, adUserID, comAuditResultText, comAuditComment, currentActivityName);
                    SetInstanceDataFields(curWorkListItem, "ApprovalResult", xmlApproval.ToXML(), true);

                    //设置最后审批历史记录

                    //xmlApproval.LoadFromXML(page.Server.HtmlDecode(lastApprovalResultXML)); 					
                    xmlApproval.LoadFromXML(lastApprovalResultXML);
                    xmlApproval.SetLastApproval(empName, adUserID, comAuditResultText, comAuditComment, currentActivityName);
                    SetInstanceDataFields(curWorkListItem, "LastApprovalResult", xmlApproval.ToXML(), true);

                    //设置审批结果
                    SetInstanceDataFields(curWorkListItem, "ComAuditComment", comAuditComment, false);
                    SetInstanceDataFields(curWorkListItem, "ComAuditResult", comAuditResultValue, false);

                    //使更新DataFields 的操作生效

                    FinishWorklistItem(curWorkListItem);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 根据旧的历史审批记录生成并设置新的历史审批记录(ApprovalResult/LastApprovalResult)
        /// </summary>
        /// <param name="page">当前页面对象</param>
        /// <param name="dgApprovalResult">显示历史记录的表格对象(在提交前要把它的绑定去掉)</param>
        /// <param name="approvalResultXML">旧审批历史记录XML</param>
        /// <param name="txtLastApprovalResult">旧的最后审批历史记录文档框对象</param>
        /// <param name="comAuditResult">审批结果(同意/重填/补充资料)</param>
        /// <param name="comAuditComment">审批意见</param>
        /// <param name="currentActivityName">当前流程步骤名称</param>
        public static void SetApprovalResult(Connection oK2Connection,
            UserProfile userProfile,
            string SN,
            string comAuditResultValue,
            string comAuditResultText,
            string comAuditComment,
            string currentActivityName)
        {
            try
            {
                //把审批意见的<>号替换掉
                comAuditComment = comAuditComment.Replace("<", "&lt;");
                comAuditComment = comAuditComment.Replace(">", "&gt;");

                string approvalResultXML = GetInstanceDataFields(oK2Connection, SN, "ApprovalResult", true);
                string lastApprovalResultXML = GetInstanceDataFields(oK2Connection, SN, "LastApprovalResult", true);
                //如果是第一次。xml是空的。则自动加上节点<?xml version="1.0" encoding="UTF-8" ?><Root><Approvals></Approvals></Root>
                if (approvalResultXML.Trim() == "")
                {
                    approvalResultXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><Root><Approvals></Approvals></Root>";
                }
                if (lastApprovalResultXML.Trim() == "")
                {
                    lastApprovalResultXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><Root><Approvals></Approvals></Root>";
                }

                string adUserID = userProfile.LoginName;
                string empName = userProfile.Empname;

                SourceCode.Workflow.Client.WorklistItem curWorkListItem = oK2Connection.OpenWorklistItem(SN);
                if (currentActivityName != null)
                {
                    XMLApproval xmlApproval = new XMLApproval();

                    //增加一个审批记录

                    xmlApproval.LoadFromXML(approvalResultXML);
                    xmlApproval.AddApproval(empName, adUserID, comAuditResultText, comAuditComment, currentActivityName);
                    SetInstanceDataFields(curWorkListItem, "ApprovalResult", xmlApproval.ToXML(), true);

                    //设置最后审批历史记录

                    //xmlApproval.LoadFromXML(page.Server.HtmlDecode(lastApprovalResultXML)); 					
                    xmlApproval.LoadFromXML(lastApprovalResultXML);
                    xmlApproval.SetLastApproval(empName, adUserID, comAuditResultText, comAuditComment, currentActivityName);
                    SetInstanceDataFields(curWorkListItem, "LastApprovalResult", xmlApproval.ToXML(), true);

                    //设置审批结果
                    SetInstanceDataFields(curWorkListItem, "ComAuditComment", comAuditComment, false);
                    SetInstanceDataFields(curWorkListItem, "ComAuditResult", comAuditResultValue, false);

                    //使更新DataFields 的操作生效

                    FinishWorklistItem(curWorkListItem);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 根据旧的历史审批记录生成并设置新的历史审批记录(ApprovalResult/LastApprovalResult) ,兼容委托
        /// </summary>
        /// <param name="page">当前页面对象</param>
        /// <param name="dgApprovalResult">显示历史记录的表格对象(在提交前要把它的绑定去掉)</param>
        /// <param name="approvalResultXML">旧审批历史记录XML</param>
        /// <param name="txtLastApprovalResult">旧的最后审批历史记录文档框对象</param>
        /// <param name="comAuditResult">审批结果(同意/重填/补充资料)</param>
        /// <param name="comAuditComment">审批意见</param>
        /// <param name="currentActivityName">当前流程步骤名称</param>
        public static void SetApprovalResult(Connection oK2Connection,
            UserProfile userProfile,
            string SN,
            string comAuditResultValue,
            string comAuditResultText,
            string comAuditComment,
            string currentActivityName,
            string managedUser,
            string sharedUser)
        {
            try
            {
                //把审批意见的<>号替换掉
                comAuditComment = comAuditComment.Replace("<", "&lt;");
                comAuditComment = comAuditComment.Replace(">", "&gt;");

                string approvalResultXML = GetInstanceDataFields(oK2Connection, SN, "ApprovalResult", true, managedUser, sharedUser);
                string lastApprovalResultXML = GetInstanceDataFields(oK2Connection, SN, "LastApprovalResult", true, managedUser, sharedUser);
                //如果是第一次。xml是空的。则自动加上节点<?xml version="1.0" encoding="UTF-8" ?><Root><Approvals></Approvals></Root>
                if (approvalResultXML.Trim() == "")
                {
                    approvalResultXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><Root><Approvals></Approvals></Root>";
                }
                if (lastApprovalResultXML.Trim() == "")
                {
                    lastApprovalResultXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><Root><Approvals></Approvals></Root>";
                }

                string adUserID = userProfile.LoginName;
                string empName = userProfile.Empname;

                SourceCode.Workflow.Client.WorklistItem curWorkListItem = GetWorkListItemBySN(oK2Connection, SN, managedUser, sharedUser); ;//oK2Connection.OpenWorklistItem(SN);
                if (currentActivityName != null)
                {
                    XMLApproval xmlApproval = new XMLApproval();

                    //增加一个审批记录


                    xmlApproval.LoadFromXML(approvalResultXML);
                    xmlApproval.AddApproval(empName, adUserID, comAuditResultText, comAuditComment, currentActivityName);
                    SetInstanceDataFields(curWorkListItem, "ApprovalResult", xmlApproval.ToXML(), true);

                    //设置最后审批历史记录


                    //xmlApproval.LoadFromXML(page.Server.HtmlDecode(lastApprovalResultXML)); 					
                    xmlApproval.LoadFromXML(lastApprovalResultXML);
                    xmlApproval.SetLastApproval(empName, adUserID, comAuditResultText, comAuditComment, currentActivityName);
                    SetInstanceDataFields(curWorkListItem, "LastApprovalResult", xmlApproval.ToXML(), true);

                    //设置审批结果
                    SetInstanceDataFields(curWorkListItem, "ComAuditComment", comAuditComment, false);
                    SetInstanceDataFields(curWorkListItem, "ComAuditResult", comAuditResultValue, false);

                    //使更新DataFields 的操作生效


                    FinishWorklistItem(curWorkListItem);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 获取用户代办事项
        /// <summary>
        /// 获取当前用户的WorkListItems
        /// </summary>
        /// <param name="oK2Connection"></param>
        /// <param name="currentUser"></param>
        /// <returns></returns>
        public static DataSet GetCurrentUserWorkListItem(Connection oK2Connection, string k2folder, string currentUser)
        {

                oK2Connection.ImpersonateUser(currentUser);

            DataSet ds = new DataSet();
            ds.Tables.Add(new DataTable());
            ds.Tables[0].Columns.Add("WorkListID", typeof(string));
            ds.Tables[0].Columns.Add("ProcInstID", typeof(string));
            ds.Tables[0].Columns.Add("RegionName", typeof(string));
            ds.Tables[0].Columns.Add("Folio", typeof(string));
            ds.Tables[0].Columns.Add("ProcessName", typeof(string));
            ds.Tables[0].Columns.Add("StartDate", typeof(string));
            ds.Tables[0].Columns.Add("CurActivityName", typeof(string));
            ds.Tables[0].Columns.Add("URL", typeof(string));
            ds.Tables[0].Columns.Add("SN", typeof(string));
            ds.Tables[0].Columns.Add("Status", typeof(string));
            ds.Tables[0].Columns.Add("OpenBy", typeof(string));
            ds.Tables[0].Columns.Add("Type", typeof(string));

            //需要考虑是否有委托事项

            SourceCode.Workflow.Client.WorklistCriteria criteria = new SourceCode.Workflow.Client.WorklistCriteria();
            criteria.Platform = "ASP";
            criteria.AddFilterField(SourceCode.Workflow.Client.WCLogical.Or, SourceCode.Workflow.Client.WCField.WorklistItemOwner, "Me", SourceCode.Workflow.Client.WCCompare.Equal, SourceCode.Workflow.Client.WCWorklistItemOwner.Me);
            //criteria.AddFilterField(SourceCode.Workflow.Client.WCLogical.Or, SourceCode.Workflow.Client.WCField.WorklistItemOwner, "Other", SourceCode.Workflow.Client.WCCompare.Equal, SourceCode.Workflow.Client.WCWorklistItemOwner.Other);
            Worklist worklist = oK2Connection.OpenWorklist(criteria);

            foreach (SourceCode.Workflow.Client.WorklistItem worklistItem in worklist)
            {
                ////忽略状态为Allocated的WorkListItem
                if (worklistItem.Status == WorklistStatus.Allocated)
                {
                    continue;
                }

                //如果当前待办事项不为指定的K2文件夹，则跳过

                //if (worklistItem.ProcessInstance.Folder != k2folder)
                if (!(k2folder.IndexOf(worklistItem.ProcessInstance.Folder) > -1))
                {
                    continue;
                }

                string folio = worklistItem.ProcessInstance.Folio;
                DataRow dr = ds.Tables[0].NewRow();
                dr["WorkListID"] = worklistItem.ID;
                dr["ProcInstID"] = worklistItem.ProcessInstance.ID.ToString();
                dr["Folio"] = folio;
                dr["RegionName"] = folio.Substring(1, folio.IndexOf("]") - 1);
                dr["ProcessName"] = worklistItem.ProcessInstance.Name;
                dr["StartDate"] = worklistItem.ProcessInstance.StartDate.ToString("yyyy-MM-dd");
                dr["CurActivityName"] = worklistItem.ActivityInstanceDestination.Description;
                dr["URL"] = worklistItem.Data;
                dr["SN"] = worklistItem.SerialNumber;
                dr["Status"] = worklistItem.Status;
                dr["OpenBy"] = worklistItem.AllocatedUser == "" ? "" : worklistItem.AllocatedUser.Replace(@"K2:CENTALINE\", "");
                dr["Type"] = "";
                ds.Tables[0].Rows.Add(dr);

            }

            return ds;

        }
        /// <summary>
        /// 获取当前用户的WorkListItems
        /// </summary>
        /// <param name="oK2Connection"></param>
        /// <param name="currentUser"></param>
        /// <returns></returns>
        public static DataSet GetCurrentUserWorkListItem(Connection oK2Connection, string currentUser)
        {
            oK2Connection.ImpersonateUser(currentUser);

            DataSet ds = new DataSet();
            ds.Tables.Add(new DataTable());
            ds.Tables[0].Columns.Add("WorkListID", typeof(string));
            ds.Tables[0].Columns.Add("ProcInstID", typeof(string));
            ds.Tables[0].Columns.Add("Folio", typeof(string));
            ds.Tables[0].Columns.Add("ProcessName", typeof(string));
            ds.Tables[0].Columns.Add("StartDate", typeof(string));
            ds.Tables[0].Columns.Add("CurActivityName", typeof(string));
            ds.Tables[0].Columns.Add("URL", typeof(string));
            ds.Tables[0].Columns.Add("SN", typeof(string));
            ds.Tables[0].Columns.Add("Status", typeof(string));
            ds.Tables[0].Columns.Add("OpenBy", typeof(string));

            //需要考虑是否有委托事项

            SourceCode.Workflow.Client.WorklistCriteria criteria = new SourceCode.Workflow.Client.WorklistCriteria();
            criteria.Platform = "ASP";
            criteria.AddFilterField(SourceCode.Workflow.Client.WCLogical.Or, SourceCode.Workflow.Client.WCField.WorklistItemOwner, "Me", SourceCode.Workflow.Client.WCCompare.Equal, SourceCode.Workflow.Client.WCWorklistItemOwner.Me);
            criteria.AddFilterField(SourceCode.Workflow.Client.WCLogical.Or, SourceCode.Workflow.Client.WCField.WorklistItemOwner, "Other", SourceCode.Workflow.Client.WCCompare.Equal, SourceCode.Workflow.Client.WCWorklistItemOwner.Other);
            Worklist worklist = oK2Connection.OpenWorklist(criteria);

            foreach (SourceCode.Workflow.Client.WorklistItem worklistItem in worklist)
            {
                ////忽略状态为Allocated的WorkListItem
                if (worklistItem.Status == WorklistStatus.Allocated)
                {
                    continue;
                }

                oK2Connection.OpenWorklistItem(worklistItem.SerialNumber, "ASP", false);
                if (worklistItem != null)
                {
                    DataRow dr = ds.Tables[0].NewRow();
                    dr["WorkListID"] = worklistItem.ID;
                    dr["ProcInstID"] = worklistItem.ProcessInstance.ID.ToString();
                    dr["Folio"] = worklistItem.ProcessInstance.Folio;
                    dr["ProcessName"] = worklistItem.ProcessInstance.Name;
                    dr["StartDate"] = worklistItem.ProcessInstance.StartDate.ToString();
                    dr["CurActivityName"] = worklistItem.ActivityInstanceDestination.Description;
                    dr["URL"] = worklistItem.Data;
                    dr["SN"] = worklistItem.SerialNumber;
                    dr["Status"] = worklistItem.Status;
                    dr["OpenBy"] = worklistItem.AllocatedUser;
                    ds.Tables[0].Rows.Add(dr);
                }
            }
            return ds;
        }
        /// <summary>
        /// 取得当前（有委托）的待办事宜
        /// </summary>
        /// <param name="oK2Connection"></param>
        /// <param name="currentUser"></param>
        /// <param name="dsShared"></param>
        /// <returns></returns>
        public static DataSet GetCurrentUserWorkListItem(Connection oK2Connection, string k2Folder, string currentUser, DataSet dsShared)
        {
            oK2Connection.ImpersonateUser(currentUser);

            DataSet ds = new DataSet();
            ds.Tables.Add(new DataTable());
            ds.Tables[0].Columns.Add("WorkListID", typeof(string));
            ds.Tables[0].Columns.Add("ProcInstID", typeof(string));
            ds.Tables[0].Columns.Add("RegionName", typeof(string));
            ds.Tables[0].Columns.Add("Folio", typeof(string));
            ds.Tables[0].Columns.Add("ProcessName", typeof(string));
            ds.Tables[0].Columns.Add("StartDate", typeof(string));
            ds.Tables[0].Columns.Add("CurActivityName", typeof(string));
            ds.Tables[0].Columns.Add("URL", typeof(string));
            ds.Tables[0].Columns.Add("SN", typeof(string));
            ds.Tables[0].Columns.Add("Status", typeof(string));
            ds.Tables[0].Columns.Add("OpenBy", typeof(string));
            ds.Tables[0].Columns.Add("Type", typeof(string));

            //需要考虑是否有委托事项

            SourceCode.Workflow.Client.WorklistCriteria criteria = new SourceCode.Workflow.Client.WorklistCriteria();
            criteria.Platform = "ASP";

            //criteria.AddFilterField(SourceCode.Workflow.Client.WCLogical.Or, SourceCode.Workflow.Client.WCField.WorklistItemOwner, "Me", SourceCode.Workflow.Client.WCCompare.Equal, SourceCode.Workflow.Client.WCWorklistItemOwner.Me);
            criteria.AddFilterField(SourceCode.Workflow.Client.WCLogical.Or, SourceCode.Workflow.Client.WCField.WorklistItemOwner, "Other", SourceCode.Workflow.Client.WCCompare.Equal, SourceCode.Workflow.Client.WCWorklistItemOwner.Other);
            Worklist worklist = oK2Connection.OpenWorklist(criteria);

            for (int i = 0; i < dsShared.Tables[0].Rows.Count; i++)
            {
                //如果当前日期不在委托期限内的，则跳过
                DateTime start, end;
                start = DateTime.Parse(dsShared.Tables[0].Rows[i]["StartDate"].ToString());
                if (string.IsNullOrEmpty(dsShared.Tables[0].Rows[i]["EndDate"].ToString()))
                {
                    end = DateTime.Parse("9999-12-31");
                }
                else
                {
                    end = DateTime.Parse(dsShared.Tables[0].Rows[i]["EndDate"].ToString());
                }

                DateTime now = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd"));
                if (now < start || now > end)
                {
                    continue;
                }

                foreach (SourceCode.Workflow.Client.WorklistItem worklistItem in worklist)
                {
                    ////忽略状态为Allocated的WorkListItem
                    if (worklistItem.Status == WorklistStatus.Allocated)
                    {
                        continue;
                    }

                    //如果当前待办事项不为指定的K2文件夹，则跳过

                    if (worklistItem.ProcessInstance.Folder != k2Folder)
                    {
                        continue;
                    }

                    if (worklistItem.AllocatedUser.Replace(@"K2:CENTALINE\", "").ToLower() != dsShared.Tables[0].Rows[i]["SharedUser"].ToString().ToLower())
                    {

                        continue;
                    }


                    string folio = worklistItem.ProcessInstance.Folio;
                    DataRow dr = ds.Tables[0].NewRow();
                    dr["WorkListID"] = worklistItem.ID;
                    dr["ProcInstID"] = worklistItem.ProcessInstance.ID.ToString();
                    dr["Folio"] = folio;
                    dr["RegionName"] = folio.Substring(1, folio.IndexOf("]") - 1);
                    dr["ProcessName"] = worklistItem.ProcessInstance.Name;
                    dr["StartDate"] = worklistItem.ProcessInstance.StartDate.ToString("yyyy-MM-dd");
                    dr["CurActivityName"] = worklistItem.ActivityInstanceDestination.Description;
                    dr["URL"] = worklistItem.Data + (worklistItem.AllocatedUser.ToLower() == oK2Connection.User.FQN.ToLower() ? "" : "&SharedUser=" + worklistItem.AllocatedUser.Replace(@"\", @"\\"));
                    dr["SN"] = worklistItem.SerialNumber;
                    dr["Status"] = worklistItem.Status;
                    dr["OpenBy"] = worklistItem.AllocatedUser.Replace(@"K2:CENTALINE\", "");
                    dr["Type"] = "委托";
                    ds.Tables[0].Rows.Add(dr);

                }
            }

            return ds;

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dataManager"></param>
        /// <param name="currentUser"></param>
        /// <returns></returns>
        public static DataSet GetWorkListSharedADUser(DataManager dataManager, string currentUser)
        {
            string sql = "";
            DataSet ds = null;
            if (dataManager == null)
            {
                dataManager = new DataManager();
                dataManager.OpenWithConfig();
                sql = string.Format(@"Select ForwardADUserID,ADUserID As SharedUser,StartDate,EndDate From VW_WF_GetSharedADUser Where ForwardADUserID = '{0}'", currentUser);
                ds = dataManager.SelectDataSet(sql);
                if (dataManager.IsClosed == false)
                {
                    dataManager.Close();
                }
            }
            else
            {
                sql = string.Format(@"Select ForwardADUserID,ADUserID As SharedUser,StartDate,EndDate From VW_WF_GetSharedADUser Where ForwardADUserID = '{0}'", currentUser);
                ds = dataManager.SelectDataSet(sql);
            }
            return ds;
        }
        #endregion

        #region 删除流程实例
        /// <summary>
        /// 删除流程实例
        /// </summary>
        /// <param name="k2ServerConnectionString"></param>
        /// <param name="procInstID"></param>
        /// <returns></returns>
        public static bool DeleteProcessInstance(string k2ServerConnectionString, int procInstID)
        {
            bool ret = false;
            WorkflowManagementServer wms = new WorkflowManagementServer();
            try
            {
                wms.Open(k2ServerConnectionString);
                ret = wms.DeleteProcessInstances(procInstID, true);
            }
            catch
            {
                ret = false;
            }
            finally
            {
                wms.Connection.Close();
                wms.Connection.Dispose();

            }
            return ret;
        }

        /// <summary>
        /// 删除流程实例，如果有错误，将返回错误信息
        /// </summary>
        /// <param name="k2ServerConnectionString"></param>
        /// <param name="procInstID"></param>
        /// <param name="errMsg"></param>
        /// <returns></returns>
        public static bool DeleteProcessInstance(string k2ServerConnectionString, int procInstID, out string errMsg)
        {
            bool ret = false;
            errMsg = "";
            WorkflowManagementServer wms = new WorkflowManagementServer();
            try
            {
                wms.Open(k2ServerConnectionString);
                ret = wms.DeleteProcessInstances(procInstID, true);
            }
            catch (Exception ex)
            {
                ret = false;
                errMsg = ex.Message;
            }
            finally
            {
                wms.Connection.Close();
                wms.Connection.Dispose();

            }

            return ret;
        }
        #endregion

        #region 修复流程
        /// <summary>
        /// 修复某个流程实例的错误

        /// </summary>
        /// <param name="k2ServerConnectionString"></param>
        /// <param name="procInstID"></param>
        /// <returns></returns>
        public static bool RepairErrorProcessInstance(string k2ServerConnectionString, int procInstID, out string errMsg)
        {
            bool ret = false;
            errMsg = "";
            WorkflowManagementServer wms = new WorkflowManagementServer();
            try
            {
                wms.Open(k2ServerConnectionString);
                ErrorProfiles oK2ErrorProfiles = wms.GetErrorProfiles();
                ErrorLogs oK2ErrorLogs = wms.GetErrorLogs(oK2ErrorProfiles[0].ID);

                foreach (ErrorLog errLog in oK2ErrorLogs)
                {

                    if (errLog.ProcInstID == procInstID)
                    {
                        string userName = System.Configuration.ConfigurationManager.AppSettings["MngUserID"].ToString();
                        ret = wms.RetryError(procInstID, errLog.ID, userName);
                        //ret = wms.RepairError(errLog.ID, errLog.CodeItem.CodeText, errLog.ProcInstID);
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                ret = false;
                errMsg = ex.Message;
            }
            finally
            {
                wms.Connection.Close();
                wms.Connection.Dispose();

            }

            return ret;
        }
        #endregion

        #region 取得错误流程列表
        /// <summary>
        /// 取得错误流程列表
        /// </summary>
        /// <param name="k2ServerConnectionString"></param>
        /// <param name="floderName"></param>
        /// <returns></returns>
        public static DataSet GetErrorProcessInstanceList(string k2ServerConnectionString, string floderName)
        {

            DataSet ds = new DataSet();
            ds.Tables.Add(new DataTable());

            ds.Tables[0].Columns.Add("ProcInstID", typeof(string));
            ds.Tables[0].Columns.Add("Folio", typeof(string));
            ds.Tables[0].Columns.Add("Source", typeof(string));
            ds.Tables[0].Columns.Add("StartDate", typeof(string));
            ds.Tables[0].Columns.Add("ErrorDate", typeof(string));
            ds.Tables[0].Columns.Add("Description", typeof(string));

            WorkflowManagementServer wms = new WorkflowManagementServer();
            try
            {
                wms.Open(k2ServerConnectionString);
                ErrorProfiles oK2ErrorProfiles = wms.GetErrorProfiles();
                ErrorLogs oK2ErrorLogs = wms.GetErrorLogs(oK2ErrorProfiles[0].ID);

                foreach (ErrorLog errLog in oK2ErrorLogs)
                {
                    if (errLog.ProcessName.IndexOf(floderName) >= 0)
                    {
                        DataRow dr = ds.Tables[0].NewRow();
                        dr["ProcInstID"] = errLog.ProcInstID.ToString();
                        dr["Source"] = errLog.ErrorItemName;
                        dr["Folio"] = errLog.Folio;
                        dr["ErrorDate"] = errLog.ErrorDate;
                        dr["Description"] = errLog.Description;
                        dr["StartDate"] = errLog.StartDate;

                        ds.Tables[0].Rows.Add(dr);
                    }
                }
            }
            catch
            {
                ds = null;
            }
            finally
            {
                wms.Connection.Close();
                wms.Connection.Dispose();

            }

            return ds;
        }
        #endregion

        #region 取得被委托的用户信息
        /// <summary>
        ///  取得设置了委托的用户信息
        /// </summary>
        /// <param name="k2ServerConnectionString"></param>
        /// <returns></returns>
        public static DataSet GetOutOfOfficeUsers(string k2ServerConnectionString)
        {
            DataSet ds = new DataSet();
            ds.Tables.Add(new DataTable());
            ds.Tables[0].Columns.Add("UserID", typeof(string));
            ds.Tables[0].Columns.Add("UserName", typeof(string));
            ds.Tables[0].Columns.Add("StartDate", typeof(string));
            ds.Tables[0].Columns.Add("EnDate", typeof(string));

            WorkflowManagementServer wms = new WorkflowManagementServer();
            try
            {
                wms.Open(k2ServerConnectionString);

                SourceCode.Workflow.Management.OOF.Users OOFUsers = wms.GetUsers(SourceCode.Workflow.Management.ShareType.OOF);

                foreach (SourceCode.Workflow.Management.OOF.User OOFUser in OOFUsers)
                {
                    SourceCode.Workflow.Management.WorklistShares wlss = wms.GetCurrentSharingSettings(OOFUser.FQN, SourceCode.Workflow.Management.ShareType.OOF);
                    foreach (SourceCode.Workflow.Management.WorklistShare wls in wlss)
                    {
                        DataRow dr = ds.Tables[0].NewRow();
                        dr["UserID"] = OOFUser.ID.ToString();
                        dr["UserName"] = OOFUser.FQN;
                        dr["StartDate"] = wls.StartDate.ToString();
                        dr["EndDate"] = wls.EndDate.ToString();
                        ds.Tables[0].Rows.Add(dr);
                    }

                }
            }
            catch
            {
                ds = null;
            }
            finally
            {
                wms.Connection.Close();
                wms.Connection.Dispose();
            }
            return ds;
        }
        #endregion

        #region 设置用户外出
        /// <summary>
        /// 
        /// </summary>
        /// <param name="k2ServerConnectionString"></param>
        /// <param name="userName"></param>
        /// <returns></returns>
        public static bool SetUserOutOfOffice(string k2ServerConnectionString, string userName)
        {
            WorkflowManagementServer wms = new WorkflowManagementServer();
            try
            {
                wms.Open(k2ServerConnectionString);

                return wms.SetUserStatus(userName, SourceCode.Workflow.Management.UserStatuses.OOF);
            }
            catch
            {
                return false;
            }
            finally
            {
                wms.Connection.Close();
                wms.Connection.Dispose();
            }
        }

        #endregion 设置用户外出

        #region 取消用户外出
        /// <summary>
        /// 
        /// </summary>
        /// <param name="k2ServerConnectionString"></param>
        /// <param name="userName"></param>
        /// <returns></returns>
        public static bool SetUserUnOutOfOffice(string k2ServerConnectionString, string userName)
        {
            WorkflowManagementServer wms = new WorkflowManagementServer();
            try
            {
                wms.Open(k2ServerConnectionString);

                return wms.SetUserStatus(userName, SourceCode.Workflow.Management.UserStatuses.Available);
            }
            catch
            {
                return false;
            }
            finally
            {
                wms.Connection.Close();
                wms.Connection.Dispose();
            }
        }

        #endregion 设置用户外出

        #region 设置用户委托
        /// <summary>
        /// 设置用户A在某个时间段内将待办事项委托给用户B、C、D......
        /// </summary>
        /// <param name="k2ServerConnectionString"></param>
        /// <param name="userName"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <param name="dsForwardUser"></param>
        public static bool SetUserOutOfOffice(string k2ServerConnectionString, string userName, string startDate, string endDate, DataSet dsForwardUser, string status)
        {
            bool ret = true;
            WorkflowManagementServer wms = new WorkflowManagementServer();
            try
            {
                wms.Open(k2ServerConnectionString);

                string k2Label = "K2:CENTALINE\\";
                SourceCode.Workflow.Management.WorklistShare worklistShare = new SourceCode.Workflow.Management.WorklistShare();
                //worklistShare.StartDate = DateTime.Parse(CentaUtil.Date8To10(startDate));
                //worklistShare.EndDate = DateTime.Parse(CentaUtil.Date8To10(endDate));
                worklistShare.StartDate = DateTime.Parse(startDate);
                worklistShare.EndDate = DateTime.Parse(endDate);
                SourceCode.Workflow.Management.WorkType workType = new SourceCode.Workflow.Management.WorkType("MyOOFWorkType");
                workType.WorklistCriteria.Platform = "ASP";

                //可以委托给多个用户

                workType.Destinations.Clear();
                for (int i = 0; i < dsForwardUser.Tables[0].Rows.Count; i++)
                {
                    workType.Destinations.Add(new SourceCode.Workflow.Management.Destination(k2Label + dsForwardUser.Tables[0].Rows[i]["ForwardADUserID"].ToString(), SourceCode.Workflow.Management.DestinationType.User));
                }

                /*WorkTypeException workTypeException = new WorkTypeException("MyOOFWorkTypeException");
                workTypeException.WorklistCriteria.Platform = "ASP";
                workTypeException.WorklistCriteria.AddFilterField(WCLogical.And, WCField.ProcessFullName, WCCompare.Equal, @"K2OOF\\K2OOFProcess");
                workTypeException.WorklistCriteria.AddFilterField(WCLogical.And, WCField.ActivityName, WCCompare.Equal, "Activity");
                workTypeException.Destinations.Add(new Destination(@"K2:K2WORKFLOW\ExceptionUser", DestinationType.User));
                workType.WorkTypeExceptions.Add(workTypeException);*/

                worklistShare.WorkTypes.Add(workType);
                ret = wms.UnShareAll(k2Label + userName);

                if (status == "OUT")
                {
                    ret = wms.ShareWorkList(k2Label + userName, worklistShare);
                    ret = ret && wms.SetUserStatus(k2Label + userName, SourceCode.Workflow.Management.UserStatuses.OOF);
                }
                if (status == "IN")
                {

                    ret = ret && wms.SetUserStatus(k2Label + userName, SourceCode.Workflow.Management.UserStatuses.Available);
                }
            }

            catch
            {
                ret = false;
            }
            finally
            {
                wms.Connection.Close();
                wms.Connection.Dispose();
            }

            return ret;
        }
        #endregion 设置用户委托

        #region 取得参与过流程审批人的姓名(审批结果为通过)
        public static string GetWorkflowApprovalEmpName(DataManager dataManager, string bizDataID, string applyType, string activityName)
        {
            string rtn = "";
            string sql = string.Format(@" Select Top 1 UserName From VW_WF_AuditHistory Where BizDataID='{0}'
                   And ApplyType = '{1}' And ActivityName='{2}'  And ApprovalResult Like '通过%'
                   Order by ApprovalDate Desc ", bizDataID, applyType, activityName);
            object obj = dataManager.SelectScalar(sql);
            if (obj != null)
            {
                rtn = obj.ToString();
            }
            return rtn;
        }

        #endregion 取得流程审批人

        #region 是否存在助理区域经理
        public static string CheckExistsAssistantRegionManager(DataManager dataManager, string deptID)
        {
            string rtn = "0";
            DataSet ds = dataManager.SelectDataSet(string.Format(@"Exec PR_GetUserInfoByRole '{0}','助理区域经理',0", deptID));
            if (ds.Tables[0].Rows.Count != 0)
            {
                rtn = "1";
            }
            else
            {
                rtn = "0";
            }
            return rtn;
        }
        #endregion 是否存在助理区域经理

        #region 绑定审批提交按钮的客户端校验事件
        public static void SetSubmitClientScript(System.Web.UI.WebControls.RadioButtonList rblComAuditResult, System.Web.UI.WebControls.Button btnSubmit)
        {
            string onclick = "";

            if (rblComAuditResult.Items.Count != 0) //如果有”通过”,”拒绝”,”补充资料”等操作选取项
            {
                onclick += "; if(CheckComAuditComment() && OnFormSubmit()){return confirm('确定进行['+getRadioButtonListSelectedText(document.getElementById('" + rblComAuditResult.ClientID + "'))+']操作？');}else return false;";

            }
            else
            {
                onclick += "; if(OnFormSubmit()){return confirm('确定进行[" + btnSubmit.Text + "]操作？');}else return false;";
            }

            btnSubmit.Attributes.Add("onclick", onclick);
        }
        #endregion

        /// <summary>
        /// 根据帐号获取用户的姓名

        /// </summary>
        /// <param name="adUserID"></param>
        /// <returns></returns>
        public static string GetEmpNameByADUserID(string adUserID)
        {
            string rtn = "";
            DataManager dm = new DataManager();
            try
            {
                dm.OpenWithConfig();
                BusinessEntiry emp = new BusinessEntiry(dm, "Employee", "empid");
                adUserID = adUserID.ToLower().Replace("centaline\\", "");

                if (emp.Open(String.Format("ADUserID='{0}' and delflag = 0", adUserID)))
                {
                    rtn = emp.GetPropertyValue("EmpName");
                }
                return rtn;
            }
            catch
            {
                throw;
            }
            finally
            {
                try
                {
                    if (dm != null && !dm.IsClosed)
                    {
                        dm.Close();
                    }
                }
                catch
                {
                }
            }
        }
    }


    [Serializable]
    public class DataFieldItemEntity
    {
        #region 构造函数

        public DataFieldItemEntity()
        {
        }
        public DataFieldItemEntity(string fieldName, string fieldValue, bool isXmlField = false)
        {
            this.FieldName = fieldName;
            this.FieldValue = fieldValue;
            this.IsXMLField = isXmlField;
        }
        #endregion

        private string _FieldName;

        public string FieldName
        {
            get { return _FieldName; }
            set { _FieldName = value; }
        }

        private string _FieldValue;

        public string FieldValue
        {
            get { return _FieldValue; }
            set { _FieldValue = value; }
        }

        private bool _IsXMLField;

        public bool IsXMLField
        {
            get { return _IsXMLField; }
            set { _IsXMLField = value; }
        }
    }
}
